简体   繁体   中英

WPF TreeView HierarchicalDataTemplate set child to active based on ItemsSource object property

I am working on a IRC client in C# WPF that has a TreeView to show the servers and channels the client is currently connected to in this format:

  • Server
    • Channel

This is my current code:

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

What I want to do now is if a Channel object loaded from ActiveChannels has it's IsActive property set to true, is set that object's TreeViewItem IsSelected property to true.

I've been looking for an answer for a couple hours now and I haven't been able to find anything that helps me achieve this, but if this question is already answered here I'm sure on of you guys would be able to point me in the right direction.

Just set binding of IsSelected property at TreeViewItem to IsActive property of your Channel object. (Ensure dataContexts to be right)

try this template instead of what you have now:

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

You will see that all items would be checked according to IsActive property

So I tried some more things out and finally found what I was looking for, which was surprisingly easy.

<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>

By using another HierarchicalDataTemplate that targets TreeViewItems created from a Channel object I am able to to correctly set the IsSelected property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM