我有一个TreeviewItem
,其style
设置为此
<Style x:Key="TreeViewItemStyle" TargetType="TreeViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TreeViewItem">
<StackPanel x:Name="stackpanel" Orientation="Horizontal">
<CheckBox x:Name="checkbox_treeview" Checked="treeView_AfterCheck" Unchecked="treeView_AfterCheck"/>
<Image x:Name="image_treeview" Width="16"/>
<local:WPFEditableTextBlock x:Name="label_TreeView" Text="{TemplateBinding Header}"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我可以通过执行此操作
来访问模板的checkbox
TreeViewItem folderNode = new TreeViewItem();
Style style = this.FindResource("TreeViewItemStyle") as Style;
folderNode.Style = style;
ControlTemplate controlTemplate = folderNode.Template;
var templatedControl = folderNode.Template.LoadContent() as FrameworkElement;
CheckBox chbx = (CheckBox)templatedControl.FindName("checkbox_treeview");
一旦我能够访问此checkbox
,我就会转到checked
事件处理程序。在此我希望能够访问包含treeViewItem
的{{1}},但我无法弄清楚如何执行此操作。请帮帮我!!!
答案 0 :(得分:0)
要从模板中定义的treeViewItem
访问checkbox
,您可以将其传递到xaml的Tag
属性中,如下所示:
<ControlTemplate TargetType="TreeViewItem">
<StackPanel x:Name="stackpanel" Orientation="Horizontal">
<CheckBox x:Name="checkbox_treeview" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}" Checked="treeView_AfterCheck" Unchecked="treeView_AfterCheck"/>
<Image x:Name="image_treeview" Width="16"/>
<local:WPFEditableTextBlock x:Name="label_TreeView" Text="{TemplateBinding Header}"/>
</StackPanel>
</ControlTemplate>
以及如何从事件处理程序中检索它:
private void treeView_AfterCheck(object sender, RoutedEventArgs e)
{
var tvi = ((sender as CheckBox).Tag as TreeViewItem);
}