WPF: Get object visualized by (hierarchical) data template
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;
精彩评论