根据数据对象使用数据模板设置颜色样式属性

Set color style using data template according to data object property

我有一个包含字符串消息和状态枚举的数据对象。 我的目标是根据状态值设置文本块的颜色。

数据模板:

<DataTemplate DataType="{x:Type interfaces_general1:AnalogPinData}" x:Key="analogSignalTestTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="135"  Text="{Binding Path=ThresholdDescriptor.Message}" Style="{StaticResource colorfulTextBlockStyleAnalogPin}" />
            </StackPanel>
</DataTemplate>

风格

        <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource emphasizableTextBlock}" x:Key="colorfulTextBlockStyleAnalogPin">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource /*need to get here to a data object property*/}, Path=??}" Value="Info">
                    <Setter Property="Foreground" Value="Green" />
                </DataTrigger>
                <DataTrigger Binding="{Binding RelativeSource= /*need to get here to a data object property*/, Path=Text}" Value="Warning">
                    <Setter Property="Foreground" Value="Orange" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

如何绑定状态属性

数据对象是:

public class AnalogPinData
{
    /// <summary>
    /// Pin information
    /// </summary>
    [PublicAPI]
    public AnalogPin Pin { get; set; }

    /// <summary>
    /// Threshold definition information
    /// </summary>
    [PublicAPI]
    public ThresholdDescriptor ThresholdDescriptor { get; set; }
}

public class ThresholdDescriptor
{
    public Range Range { get; set; }

    [PublicAPI]
    public StatusIndicator Status { get; set; }

    [PublicAPI]
    public string Message { get; set; }
}

我需要在绑定中设置 Message 和 Status 道具。

谢谢!

由于模板数据类型的实例是DataTemplateDataContext,而TextBlock是这个模板中的一个元素,所以TextBlock会隐式继承这个 DataContextTextBlockDataContextAnalogPinData.

的实例

因此绑定到 TextBlock 元素的 DataContext 解决了问题:

<Style TargetType="TextBlock">
  <Style.Triggers>
    <DataTrigger Binding="{Binding ThresholdDescriptor.Status}" Value="Info">
      <Setter Property="Foreground" Value="Green" />
    </DataTrigger>
  </Style.Triggers>
</Style>

或者直接在 DataTemplate 中定义触发器:

<DataTemplate DataType="{x:Type interfaces_general1:AnalogPinData}" x:Key="analogSignalTestTemplate">
  <TextBlock x:Name="StatusMessageTextBlock" Text="{Binding Path=ThresholdDescriptor.Message}" />

  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding ThresholdDescriptor.Status}" Value="Info">
      <Setter TargetName="StatusMessageTextBlock" Property="Foreground" Value="Green" />
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>