private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set
{
if (_isSelected == value) return;
_isSelected = value;
RaisePropertyChanged(nameof(IsSelected));
if (HasChildren)
{
foreach (var child in Children)
{
child.IsSelected = value;
}
}
if (Parent != null)
{
Parent.UpdateSelected();
}
}
}
private void UpdateSelected()
{
var allChildrenSelected = Children.All(c => c.IsSelected);
if (allChildrenSelected && Children.Any())
{
_isSelected = true;
RaisePropertyChanged(nameof(IsSelected));
}
else
{
var anyChildSelected = Children.Any(c => c.IsSelected);
_isSelected = anyChildSelected;
RaisePropertyChanged(nameof(IsSelected));
}
if (Parent != null)
{
Parent.UpdateSelected();
}
}
其中,MyItems是ViewModel中的ObservableCollection,其中包含TreeView和CheckBox的数据源。
在TreeView中,如果选择父节点,则其所有子节点都将被选中。如果取消选择父节点,则其所有子节点都将取消选中。在ViewModel中,UpdateSelected方法用于确定子节点和父节点的选中状态。