scor4er
scor4er

Reputation: 1589

How to bind a dictionary item property?

I want to make something like this:

<Controls:TreeView>
   <Controls:TreeViewItem Header="Persons" 
         Visibility="{Binding Items[Persons], Path=IsVisible, Converter={StaticResource toVisiblityConverter}}"/>
   ...
</Controls:TreeView>

(TreeView DataContext bind to the ViewModel that contain dictionary. And value of the dictionary item have property IsVisible).

This doesn't work: path property setted more than once. How can I avoid this?

Upvotes: 1

Views: 414

Answers (1)

Lukasz M
Lukasz M

Reputation: 5723

I suppose you want to hide or show multiple tree items based on IsVisible value in the specific key. There are few methods to achieve that.

  • You can preserve the default tree part of the template and generate a TreeViewItem for each column. You can do it like this:

    <TreeView x:Name="treeCtrl" Background="LightBlue" HorizontalAlignment="Stretch" Width="300" Height="400" VerticalAlignment="Stretch" Margin="0">
        <TreeViewItem Visibility="{Binding Value.IsVisible}">
            <TextBlock Foreground="Black" Text="{Binding Key}" />
        </TreeViewItem>
    </TreeView>
    
  • You can create item template. It's a template that is generated for each item in the data source. In that template you should have an easy access to one item from the dictionary.

  • Another method that may work, would be writing another converter that would accept the whole dictionary object and item name as a parameter. Then it could get the value in the c# code and return the visibility. This way you can explicitly define column you want to get the value for. Then you could use it like this:

    <Controls:TreeView>
        <Controls:TreeViewItem Header="Persons" Visibility="{Binding Items, Converter={StaticResource dictionaryToVisibilityConverter}, ConverterParameter=Persons}"/>
    </Controls:TreeView>
    

Upvotes: 1

Related Questions