I have a data object which contains a string message and a status enum. my goal is to set the color of a textblock according to status value.
the data template:
<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>
the style
<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>
how can i do a binding to the status proerty
the data object is:
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; }
}
I need the Message and Status props to set in the binding.
thanks!
CodePudding user response:
Since the instance of the template's data type is the DataContext
of the DataTemplate
and the TextBlock
is an element in this template, the TextBlock
will implicitly inherit this DataContext
i.e. the DataContext
of TextBlock
is the instance of AnalogPinData
.
Thus binding to the TextBlock
element's DataContext
solves the problem:
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding ThresholdDescriptor.Status}" Value="Info">
<Setter Property="Foreground" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
Alternatively define the triggers directly in the 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>