如何在WPF中的复选框上获取当前元素 [英] How to get current element on checkbox in WPF

查看:36
本文介绍了如何在WPF中的复选框上获取当前元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以在Checked"事件触发时,在给定以下代码的代码中获取当前的MyClass"元素:

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>

我希望能够在选中复选框时获取树视图当前元素的所有数据.请注意,MyClass"可以有任意数量的属性,我希望能够访问它们.我有什么办法可以做到这一点吗?

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?

推荐答案

我建议坚持使用 MVVM 方法并处理项目的 ViewModel 中选中状态的更改,但在您想要的代码背后可以通过路由事件.

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.

在您的 TreeView 中订阅 CheckBox.Checked 路由事件:

In your TreeView subscribe to CheckBox.Checked routed event:

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

在后面的代码中,您可以将对应的 CheckBox 作为 OriginalSource 字段,并访问其 DataContext,即 MyClass 的一个实例:

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

这篇关于如何在WPF中的复选框上获取当前元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆