Search code examples
c#.netwpftreeviewitemhierarchicaldatatemplate

How to get this binding for item instead of TreeViewItem?


I got the following code :

<HierarchicalDataTemplate x:Key="AssignedRate" ItemsSource="{Binding Children}" DataType="{x:Type local:UnitRateCatElement}">
    <ContentControl>
        <ContentControl.Template>
            <ControlTemplate>
                <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}">
                    <TextBlock Text="{Binding Category.Description}" />
                    <StackPanel.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Add Unit Rate"
                                      Command="{Binding Path=PlacementTarget.Tag.AddUnitRateCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                </StackPanel>
            </ControlTemplate>
        </ContentControl.Template>
        <ContentControl.Style>
            <Style TargetType="{x:Type ContentControl}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=IsDefined, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}" Value="True">
                        <Setter Property="Template">    
                            <Setter.Value>
                                <ControlTemplate>
                                    <TextBlock Text="Hello, it works!" />
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</HierarchicalDataTemplate>

The binding in the line : <DataTrigger Binding="{Binding Path=IsDefined, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}" Value="True">

is incorrect (VS says so). How can I get this to work? The class local:UnitRateCatElement does have a IsDefined property. But I cannot get the binding right to point to that object. How can I get this binding right?


Solution

  • Try

    Binding="{Binding Path=DataContext.IsDefined, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"