如何在XAML中检查数据触发器中的文本块文本值

jvidinwx  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(131)

我想检查文本块的文本值,如果值是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>
eivnm1vs

eivnm1vs1#

试试这个:

<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属性所指定的值。

qyswt5oh

qyswt5oh2#

注意事项:

此答案基于answer provided by 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>
wfsdck30

wfsdck303#

根据您的意见

我想要的是。我必须检查文本块文本,如果文本块文本是颜色代码,然后分配该颜色代码到前景。就是这样
如果Binded文本值是Color代码,则此操作将更改TextblockForegroundColor,否则default color将更改为shown

<TextBlock Text="{Binding Text}" Foreground="{Binding Text, RelativeSource=
 {RelativeSource Self}}"/>

<TextBlock Text="#0FFFFF" Foreground="{Binding Text, RelativeSource=
{RelativeSource Self}}"/>

相关问题