gpt4 book ai didi

c# - WPF GetTemplateChild 获取 Nullrefrence 异常

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:33 26 4
gpt4 key购买 nike

您好,我正在构建一个控件,我需要在后面的代码中访问复选框,但是我得到了空错误

这是我的控制

<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)
{

}
}

当我使用下面的代码时,我没有得到 null 错误,但在运行时没有控制

static CheckTreeView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CheckTreeView),
new FrameworkPropertyMetadata(typeof(CheckTreeView)));
}

最佳答案

订阅每个 CheckBox 的 Click 事件:

    public partial class CheckTreeView : TreeView
{
public CheckTreeView()
{
InitializeComponent();
processNode(this);
}


void processNode(ItemsControl node)
{
node.ItemContainerGenerator.StatusChanged += (sender, args) =>
{
ItemContainerGenerator itemContainerGenerator = ((ItemContainerGenerator)sender);
if (itemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
for (int i = 0; i < itemContainerGenerator.Items.Count; i++)
{
TreeViewItem treeViewItem =
(TreeViewItem) itemContainerGenerator.ContainerFromIndex(i);

treeViewItem.Loaded += (o, eventArgs) =>
{
CheckBox checkBox = FindVisualChild<CheckBox>(treeViewItem);
checkBox.Click += CheckBox_Click;
};

processNode(treeViewItem);
}
}
};
}

public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child is T)
{
return (T)child;
}

T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}

private void CheckBox_Click(object sender, RoutedEventArgs e)
{

}
}

请注意,如果您使用 ObservableCollection 作为项目源,您应该处理该集合中的更改:订阅添加项目的事件,取消订阅删除项目的事件。

关于c# - WPF GetTemplateChild 获取 Nullrefrence 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59282179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com