Conditional formating of a TextBlock within a Listbox’s DataTemplate

前端 未结 2 624
庸人自扰
庸人自扰 2021-01-23 11:14

It’s my first wcf & I’m running into some trouble with what seems to be a basic XAML concept.

Somehow the DataTrigger / Binding in the “PriorityStyle” is not working

相关标签:
2条回答
  • 2021-01-23 11:39

    as @HighCore mentioned not sure where your setting the Source for your ListBox, but provided your binding works in the Style for ListBoxItem you can try a work-around

    <Style x:Key="PriorityStyle" TargetType="TextBlock" >
        <Setter Property="Foreground"
              Value="Black" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding DataContext.Priority, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" Value="High">
                <Setter Property="Foreground" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
    

    but your also binding Priority property to Text in the TextBlock with PriorityStyle anyways. So you could also just do:

    <Style x:Key="PriorityStyle"
           TargetType="TextBlock">
      <Setter Property="Foreground"
              Value="Black" />
      <Style.Triggers>
        <Trigger Property="Text"
                 Value="High">
          <Setter Property="Foreground"
                  Value="Red" />
        </Trigger>
      </Style.Triggers>
    </Style>
    

    this way you don't even need a binding traversing through your element tree

    0 讨论(0)
  • 2021-01-23 12:00

    I found out the real issue to my problem. It was not in fact a binding issues but a Style issue.

    I didn’t include it in the original XAML as I did some wrongful cleaning in order to make it clearer. I was including in my Textblock a “Foreground” attribute an this last one was indeed overriding my style attribute. Removing it and including the “Default Foreground” Value in the Style Setter was the answer. Beginners mistake.

    So, kudos to Viv, for pointing out the right direction & for the nice “RelativeSource” example. And sorry again for my bad question, a lesson learned here.

        <Style x:Key="PriorityStyle" TargetType="TextBlock" >
            <Setter Property="Foreground" Value="#6c6d6f" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Priority}" Value="Critical">
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    
        <TextBlock Name="Summary" Text="{Binding _Summary}" Style="{StaticResource PriorityStyle}" />
    
    0 讨论(0)
提交回复
热议问题