只有在选中父级时,才能使用带复选框子节点的wpf / telerik-treeview

时间:2017-02-16 02:39:44

标签: wpf checkbox telerik treeview treeviewitem

假设我有一个TreeView绑定项目源(可观察集合),我有这样的事情:http://docs.telerik.com/devtools/wpf/controls/radtreeview/how-to/howto-tri-state-mvvm

并且每个项目(包括父视图)都有一个复选框和名称(字符串)。

我想仅在检查父节点时才使子节点可用。

如果未选中父级,则也将取消选中所有子节点。

有没有办法实现这个目标?谢谢!

1 个答案:

答案 0 :(得分:1)

无法检查链接,但是,这是一个有效的示例,我认为您应该遵循以下结构:

查看

<Grid>
    <TreeView DataContext="{Binding}" ItemsSource="{Binding Models}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type local:ModelView}" ItemsSource="{Binding Models}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <CheckBox IsChecked="{Binding IsChecked}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid> 

<强>模型

public class Model : INotifyPropertyChanged
{
    bool _isChecked;
    public bool IsChecked { get { return _isChecked; } set {
            _isChecked = value;
            RaisePropertyChanged("IsChecked");
            if (_isChecked == false)
                unCheckOthers();
        } }
    void unCheckOthers()
    {
        if (_models != null)
            foreach (var m in _models)
                m.IsChecked = false;
    }

    Model[] _models;
    public Model[] Models { get { return _models; } set { _models = value; RaisePropertyChanged("Models"); } }

    string _name;
    public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    void RaisePropertyChanged(string propname)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
    }
}

查看模型

public class ViewModel
{
    public ViewModel()
    {
        _models = new ObservableCollection<Model>();
    }
    ObservableCollection<Model> _models;
    public ObservableCollection<Model> Models { get { return _models; } set { _models = value; } }
}

主窗口

    public MainWindow()
    {
        InitializeComponent();

        ViewModel mv = new ViewModel();
        Model m1 = new Model() { Name = "model1", IsChecked = true, Desc = "None1" };
        Model m2 = new Model() { Name = "model2", IsChecked = true, Desc = "None2" };
        Model m3 = new Model() { Name = "model3", IsChecked = true, Desc = "None3" };
        Model m4 = new Model() { Name = "model4", IsChecked = true, Desc = "None4", Models = new Model[2] {m1,m2} };
        Model m5 = new Model() { Name = "model5", IsChecked = true, Desc = "None5", Models = new Model[2] { m4, m3 } };
        mv.Models = new ObservableCollection<Model>() { m5 };
        this.DataContext = mv;
    }