Search code examples
wpfmvvmbindinguser-controlshierarchicaldatatemplate

How to bind a property of ViewModel to an element in HierarchicalDataTemplate of a Treeview?


How to bind a property of ViewModel to an element in HierarchicalDataTemplate of a Treeview (the property is is out of HierarchicalDataTemplate.Itemsource)

this is the example and the probelm is in this line: Visibility="{Binding IsCheckBoxVisible , RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Converter={StaticResource debuger}}"/>

<UserControl ....>
<Grid>
    <TreeView ItemsSource="{Binding Roots}" Grid.Row="0">
        <TreeView.ItemContainerStyle>
        </TreeView.ItemContainerStyle>
        <TreeView.ItemTemplate >
            <HierarchicalDataTemplate ItemsSource="{Binding ConfigedChildren}">
                <StackPanel Orientation="Horizontal" >
                    <CheckBox IsChecked="{Binding IsChecked}" Visibility="{Binding IsCheckBoxVisible, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Converter={StaticResource debuger}}"/>
                    <Label Content="{Binding Title}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>


Solution

  • <CheckBox IsChecked="{Binding IsChecked}" Visibility="{Binding DataContext.IsCheckBoxVisible, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Converter={StaticResource debuger}}"/> 
    

    Use DataContext.IsCheckBoxVisible. Hope this will work