嗨,我正在构建一个控件,我需要访问后面代码中的复选框,但出现空错误
这是我的控制权
<Style TargetType="TreeViewItem" x:Key="CheckTreeViewItem" >
<Setter Property="IsExpanded" Value="{Binding Path=IsExpanded,Mode=TwoWay}"/>
</Style>
<Style TargetType="local:CheckTreeView">
<Setter Property="ItemContainerStyle" Value="{StaticResource CheckTreeViewItem}"/>
<Setter Property="ItemTemplate">
<Setter.Value>
<HierarchicalDataTemplate DataType="{x:Type local:CheckTreeSource}" ItemsSource="{Binding Children}">
<CheckBox x:Name="PART_CheckBox" Margin="1" IsChecked="{Binding IsChecked}">
<TextBlock Text="{Binding Text}"/>
</CheckBox>
</HierarchicalDataTemplate>
</Setter.Value>
</Setter>
</Style>
这就是我的访问控制方式
[TemplatePart(Name = CheckBox_Key, Type = typeof(CheckBox))]
public partial class CheckTreeView : TreeView
{
private const string CheckBox_Key = "PART_CheckBox";
CheckBox checkBox;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
checkBox = GetTemplateChild(CheckBox_Key) as CheckBox;
checkBox.Click += CheckBox_Click;
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
}
}
当我使用以下代码时,在运行时没有空错误,但没有控件
static CheckTreeView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CheckTreeView),
new FrameworkPropertyMetadata(typeof(CheckTreeView)));
}
CheckBox_Key
元素不是CheckTreeView.ControlTemplate
的一部分。它将多次出现在树视图节点中。 GetTemplateChild
找不到
我想说ItemTree中CheckBox与CheckTreeView中间,您需要更改TreeViewItem.Template
并在其中添加CheckBox。它对GetTemplateChild毫无帮助,但是是一种使用chechboxes构建可重用TreeView的更合乎逻辑的方法。
要订阅每个CheckBox的Click事件: