我正在尝试根据它的值更新textblock的颜色。似乎很简单但不起作用。
这是文本块xaml。
<TextBlock
Grid.Column="1"
Grid.Row="1"
Text="{Binding Path=GL, StringFormat={}{0:N0}}"
HorizontalAlignment="Left"
FontFamily="Verdana"
Foreground="Tomato"
FontWeight="Bold"
VerticalAlignment="Center"
Margin="5,2,5,0"
FontSize="18"
>
<TextBlock.Resources>
<converters:ColorConverter x:Key="CoConverter"></converters:ColorConverter>
</TextBlock.Resources>
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource ResourceKey=CoConverter}}" Value="true">
<Setter Property="TextBlock.Foreground" Value="LimeGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
转换器
public class ColorConverter : MarkupExtension, IValueConverter
{
#region IValueConverter Members
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
if (value == null)
return false;
if (value.ToString().Length == 0)
return false;
if (System.Convert.ToDouble(value) >= 0)
return true;
return false;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
转换器看起来不错,但由于某种原因触发器不适用。
答案 0 :(得分:6)
<TextBlock
Grid.Column="1"
Grid.Row="1"
Text="{Binding Path=GL, StringFormat={}{0:N0}}"
HorizontalAlignment="Left"
FontFamily="Verdana"
FontWeight="Bold"
VerticalAlignment="Center"
Margin="5,2,5,0"
FontSize="18"
>
<TextBlock.Resources>
<converters:ColorConverter x:Key="CoConverter"></converters:ColorConverter>
</TextBlock.Resources>
<TextBlock.Style>
<Style>
<Setter Property="TextBlock.Foreground" Value="Tomato" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource ResourceKey=CoConverter}}" Value="true">
<Setter Property="TextBlock.Foreground" Value="LimeGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
您需要在样式中设置Foreground属性,以便在运行时动态更改它。
答案 1 :(得分:0)
在指定转换器时,您似乎缺少大括号内的StaticResource:
Converter={StaticResource converters:ColorConverter}
答案 2 :(得分:0)
如果您尝试动态更改属性值,则相应的属性必须仅保留在 Setter 标记中。
<TextBlock>
<TextBlock.Style>
<Style>
<Setter Property="TextBlock.Foreground" Value="Tomato" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource ResourceKey=CoConverter}}" Value="true">
<Setter Property="TextBlock.Foreground" Value="LimeGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
但不能同时在 TextBlock和Setter 标签中使用。为您的示例精确起见,按照我的代码中的说明,删除TextBlock标记内的Foreground属性。