views:

437

answers:

1

Hi,

I'm very new in WPF. I've got a ListBox where I want to set a template for an item (I called it Person). A TextBlock is to be used. The person has to public Properties: "Foreground" and "IsOnline". If "IsOnline" is true, I would use the "Foreground" property of the person, otherwise "Gray". That's all. My first template is:

<DataTemplate x:Key="UnselectedPersonTemplate" DataType="{x:Type o:Person}">
    <TextBlock Text="{Binding Path=Name}" Foreground="{Binding Path=Foreground}" Margin="1">
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=IsOnline}" Value="False">
                <Setter Property="TextBlock.Foreground" Value="Gray" />
            </DataTrigger>
        </DataTemplate.Triggers>
</DataTemplate>

Of course, this doesn't work. There is no exception, but also not the expected result. Then I tried to use the Trigger for the TextBlock, but there will be an exception, that I can't use DataTriggers (only EventTriggers) for that.

Thanks for any advice! :)

+2  A: 

Give your TextBlock a name and set TargetName property of the setter to that name.

<DataTemplate x:Key="UnselectedPersonTemplate" DataType="{x:Type o:Person}">
    <TextBlock x:Name="tb" Text="{Binding Path=Name}" 
          Foreground="{Binding Path=Foreground}" Margin="1" />
    <DataTemplate.Triggers>
       <DataTrigger Binding="{Binding Path=IsOnline}" Value="False">
          <Setter TargetName="tb" Property="Foreground" Value="Gray" />
       </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>
idursun
Thanks a lot. This worked for me.