开发者

WPF: Get object visualized by (hierarchical) data template

开发者 https://www.devze.com 2023-03-26 17:34 出处:网络
I\'ve got a TreeView with a couple of items in it. The items are visualized by a simple hierarchical data template, like this:

I've got a TreeView with a couple of items in it. The items are visualized by a simple hierarchical data template, like this:

<HierarchicalDataTemplate x:Key="instanceTe开发者_C百科mplate">
  <CheckBox Checked="InstanceCheckChanged" Unchecked="InstanceCheckChanged">
    <Label>Hello World!</Label>
  </CheckBox>
</HierarchicalDataTemplate>

As you can see I've added an event handler, here's the code behind:

private void InstanceCheckChanged(object sender, RoutedEventArgs e)
{
  CheckBox checkBox = (CheckBox)sender;
}

In this event handler, the sender of the event is obviously the check box itself, however the checkbox is actually visualizing my normal object. My question is, how do I get the object that the checkbox visualized? Preferably I would like to have a method with a signature like this:

public MyObject GetMyObject(UIElement sender);

Is this possible in WPF, or is there a clean way to store some metadata so that I know which MyObject was checked?


Your CheckBox's DataContext will be the object that it's representing:

var myObject = ((CheckBox)sender).DataContext as MyObject;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号