views:

201

answers:

1

I have a Treeview showing Xml data where each element is wrapped in a class that exposes IsExpanded, the wrapped XElement's Name and Value and a boolean MatchesFilter which is set if the element matches a specific filter; I'd like to change the foreground color if MatchesFilter is true.

What I currently have is:

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Width="110" Foreground="Blue" Text="{Binding Name}" />
            <TextBlock Foreground="{Binding Foreground}" Text="{Binding Value}" />
        </StackPanel>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>

where the Foreground color is being set in the code-behind, which works just fine but is hardly in the spirit of WPF! How do I do this properly?

Edit: Thank you, exactly like that, now I know which chapter to read.

+1  A: 

Something like this?

<TextBlock Name="tbkValue" Text="{Binding Value}"/>

...

<HierarchialDataTemplate.Triggers>
  <DataTrigger Binding="{Binding Path=MatchesFilter}" Value="True">
      <Setter TargetName="tbkValue" Property="Foreground" Value="Red"/>
  </DataTrigger>
</HierarchialDataTemplate.Triggers>

You can also create the trigger as a resource and share it between different templates.

Sergey Aldoukhov