【问题标题】:WPF TreeView HierarchicalDataTemplate set child to active based on ItemsSource object propertyWPF TreeView HierarchicalDataTemplate 根据 ItemsSource 对象属性将子项设置为活动
【发布时间】:2015-03-08 01:47:51
【问题描述】:

我正在使用 C# WPF 开发一个 IRC 客户端,它有一个 TreeView 来显示客户端当前以这种格式连接到的服务器和通道:

  • 服务器
    • 频道

这是我当前的代码:

<HierarchicalDataTemplate DataType="{x:Type IRCLib:ServerConnection}"
                          ItemsSource="{Binding Path=ActiveChannels}">
    <TreeViewItem Header="{Binding Path=Config.ServerName}" Foreground="Black"/>
</HierarchicalDataTemplate>

我现在要做的是,如果从 ActiveChannels 加载的 Channel 对象的 IsActive 属性设置为 true,则将该对象的 TreeViewItem IsSelected 属性设置为 true。

我已经找了几个小时的答案了,但我找不到任何可以帮助我实现这一目标的东西,但如果这个问题已经在这里得到了回答,我相信你们会是能够为我指明正确的方向。

【问题讨论】:

    标签: c# wpf treeview


    【解决方案1】:

    只需将 TreeViewItem 的 IsSelected 属性绑定到 Channel 对象的 IsActive 属性。 (确保dataContexts正确)

    试试这个模板,而不是你现在拥有的:

    <HierarchicalDataTemplate DataType="{x:Type IRCLib:ServerConnection}"
                          ItemsSource="{Binding Path=ActiveChannels}">
            <CheckBox IsChecked="{Binding IsActive}" Content="{Binding Path=Config.ServerName}" Foreground="Black"/>
        </HierarchicalDataTemplate>
    

    您将看到所有项目都将根据 IsActive 属性进行检查

    【讨论】:

    • 究竟是什么不起作用,因为我试过了,一切都按预期工作
    • 这就是您提供的模板发生的情况:Image
    【解决方案2】:

    所以我尝试了更多的东西,终于找到了我想要的东西,这非常容易。

    <TreeView.Resources>
    
        <HierarchicalDataTemplate DataType="{x:Type IRCLib:ServerConnection}"
                                  ItemsSource="{Binding Path=ActiveChannels}">
              <TreeViewItem Header="{Binding Path=Config.ServerName}"
                            Foreground="Black"
                            IsExpanded="True"/>
        </HierarchicalDataTemplate>
    
        <HierarchicalDataTemplate DataType="{x:Type IRCLib:Channel}">
              <TreeViewItem Header="{Binding Path=Name}"
                            IsSelected="{Binding Path=IsActive}"/>
        </HierarchicalDataTemplate>
    
    </TreeView.Resources>
    

    通过使用另一个以从 Channel 对象创建的 TreeViewItems 为目标的 HierarchicalDataTemplate,我能够正确设置 IsSelected 属性。

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多