如果值为 xyz,我想检查文本块的文本值。 我不想要任何操作,但如果文本值为"#FF84312F",我想将此文本设置为文本的前景色。 下面是我的代码。 我怎样才能做到这一点.请帮助我。
<TextBlock Text="#FF84312F">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Text, RelativeSource={RelativeSource Self}}" Value="*#">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
试试这个:
<TextBlock Text="#FF84312F">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{Binding Text,RelativeSource={RelativeSource Self}}" />
</Style>
</TextBlock.Style>
</TextBlock>
或者这个:
<TextBlock Text="#FF84312F">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="Text" Value="#FF84312F">
<Setter Property="Foreground" Value="{Binding Text,RelativeSource={RelativeSource Self}}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
它将无条件或有条件地(使用Trigger
(将Foreground
设置为Text
属性指定的值。
注意:
此答案基于mm8提供的答案的评论
您可以使用转换器将字符串转换为SolidColorBrush
:
转换器类别:
public class TextToSolidColorBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var color = Brushes.Black;
try
{
var converted = new BrushConverter().ConvertFromString(value?.ToString());
color = converted != null ? (SolidColorBrush) converted : Brushes.Black;
}
catch (Exception e)
{
// ignored
}
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML:
<Window.Resources>
<local:TextToSolidColorBrushConverter x:Key="TextToSolidColorBrushConverter"/>
</Window.Resources>
<TextBlock Text="Any text">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{Binding Text,RelativeSource={RelativeSource Self}, Converter={StaticResource TextToSolidColorBrushConverter}}" />
</Style>
</TextBlock.Style>
</TextBlock>
基于您的评论:
我想要的是.我必须检查文本块文本以及文本块文本 是颜色代码,然后将该颜色代码分配给前景。就是这样
如果文本值是Color
代码Binded
这将更改Textblock
Foreground
Color
default color
否则shown
。
<TextBlock Text="{Binding Text}" Foreground="{Binding Text, RelativeSource=
{RelativeSource Self}}"/>
或
<TextBlock Text="#0FFFFF" Foreground="{Binding Text, RelativeSource=
{RelativeSource Self}}"/>