WPF 的TreeView的TreeViewItem下动态生成TreeViewItem

树形结构仅部分需要动态生成TreeViewItem的可以参考本文。

xaml页面

复制代码
<TreeView MinWidth="220" >
    <TreeViewItem Header="功能列表" ItemsSource="{Binding Functions}">
        <TreeViewItem.ItemTemplate>
            <HierarchicalDataTemplate>
                <WrapPanel>
                    <CheckBox IsChecked="{Binding IsSelect}"/>
                    <Label Content="{Binding Name}"/>
                </WrapPanel>
            </HierarchicalDataTemplate>
        </TreeViewItem.ItemTemplate>
    </TreeViewItem>
</TreeView>

对象类:

复制代码
public class SelectFunction : NotifyPropertyChangedBaseClass
{
    private bool isselect;
    /// <summary>
    /// 是否选中
    /// </summary>
    public bool IsSelect
    {
        get { return isselect; }
        set
        {
            isselect = value;
            OnPropertyChanged();
        }
    }
    public Guid Id { get; set; }

    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            OnPropertyChanged();
        }
    }
}

对象类继承的通知类:

复制代码
public class NotifyPropertyChangedBaseClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyname = "")//通过该方法可以直接获取调用者的名称 前提是需要有默认参数
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }
}

XAML绑定的集合

复制代码
 private ObservableCollection<SelectFunction> functions;
 /// <summary>
 /// 可选的功能列表
 /// </summary>
 public ObservableCollection<SelectFunction> Functions
 {
     get { return functions; }
     set
     {
         functions = value;
         OnPropertyChanged();
     }
 }

//这只是集合的定义,自己给集合赋值

最终效果,我这没有用其自带的属性事件去判断是否选中,而是采用对象类中的IsSelect的值来判断的,仅供参考。

相关推荐
贾修行2 小时前
.NET 全栈开发学习路线:从入门到分布式
c#·.net·wpf·asp.net core·web api·winforms·services
晓13132 小时前
第四章:Redis实战应用及常见问题(下篇)
java·数据库·缓存·wpf
掘根1 天前
【jsonRpc项目】客户端的Requestor模块,RpcCaller模块
wpf
FuckPatience1 天前
WPF ListBoxItem绑定自己在ListBox中的顺序
wpf
天才奇男子2 天前
LVS原理及部署
linux·运维·云原生·wpf·lvs·linux chrony
予枫的编程笔记2 天前
【Redis实战进阶篇1】Redis 分布式锁:从手写实现到 Redisson 最佳实践
redis·分布式·wpf
小北方城市网3 天前
Spring Cloud Gateway 生产级实践:高可用架构、灰度发布与故障排查
spring boot·redis·分布式·缓存·架构·wpf
ujainu3 天前
Flutter for OpenHarmonyOS 前置知识:Dart语言详解(下)
flutter·wpf·harmonyos
bugcome_com3 天前
WPF 数据模板(DataTemplate):优雅实现数据与 UI 的解耦
ui·wpf
小北方城市网4 天前
Redis 分布式锁与缓存三大问题解决方案
spring boot·redis·分布式·后端·缓存·wpf·mybatis