这个实现稍微有些复杂,但理论上是可行的:
private void TreeViewControl_Loaded(object sender, RoutedEventArgs e)
{
if (!(sender is TreeView treeViewControl))
{
return;
}
// 使用 CommunityToolkit.WinUI.Extensions 包中的 FindDescendants 方法获取 TreeView 的所有后代元素,并转换为 TreeViewItem 集合
IEnumerable<TreeViewItem> rootItems = treeViewControl
.FindDescendants()
.OfType<TreeViewItem>();
foreach (TreeViewItem item in rootItems)
{
// 查找该 TreeViewItem 中是否存在 CheckBox 后代元素
if (item.FindDescendant<CheckBox>() is not CheckBox checkBox)
{
continue;
}
// 将 CheckBox 的可见性设置为隐藏,并禁用鼠标点击检测
checkBox.Visibility = Visibility.Collapsed;
checkBox.IsHitTestVisible = false;
// 注册 CheckBox 可见性属性的更改回调,当其发生改变时,将其重新设置为隐藏
checkBox.RegisterPropertyChangedCallback(
CheckBox.VisibilityProperty,
(_, _) =>
{
checkBox.Visibility = Visibility.Collapsed;
});
}
}
注意:
FindDescendants
方法来源于 CommunityToolkit.WinUI.Extensions NuGet 包。