How to get current element on checkbox in WPF

让人想犯罪 __ 提交于 2019-12-12 02:59:04

问题


is there any way to, on "Checked" event fire, get the current "MyClass" element in the code behind given the code below:

<TreeView Name="TreeViewName">
            <TreeView.Resources >
                <HierarchicalDataTemplate DataType="{x:Type local:MyClass}" ItemsSource="{Binding Children}">
                    <StackPanel Orientation="Horizontal">
                        <CheckBox IsChecked="{Binding Checked}" VerticalAlignment="Center" Checked="OnExplorerCheck" ></CheckBox>
                        <Image Source="{Binding Icon}" Height="15" Margin="5,0,0,0"></Image>
                        <Label Content="{Binding Name}"></Label>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>

I'd like to be able to, upon checking a checkbox, get all of the data of the current element of the tree view. Note that "MyClass" can have any number of properties, and I'd like to be able to access them all. Is there any way for me to do this?


回答1:


I'd suggest to stick to MVVM approach and handle changes of checked state in the ViewModel of the item, but in code behind what you want could be achieved with routed events.

In your TreeView subscribe to CheckBox.Checked routed event:

<TreeView Name="TreeViewName" CheckBox.Checked="TreeViewName_Checked">

In code behind you can reach corresponding CheckBox as OriginalSource field, and access to its DataContext, that would be an instance of MyClass:

    private void TreeViewName_Checked(object sender, RoutedEventArgs e)
    {
        var checkBox = e.OriginalSource as CheckBox;

        MyClass dataContext = checkBox?.DataContext as MyClass;

        if (dataContext != null)
        {
            // Do something with MyClass instance
        }
    }


来源:https://stackoverflow.com/questions/36190204/how-to-get-current-element-on-checkbox-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!