How to get current element on checkbox in WPF

2019-09-05 21:52发布

问题:

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
        }
    }