如何有条件地格式化WPF TextBlock?

时间:2010-04-26 23:46:14

标签: c# wpf xaml

我有一个绑定到字符串的WPF TextBlock。 如果该字符串为空,我希望TextBlock以另一种颜色显示警告消息。

这在代码中很容易做到,我想知道是否有一个优雅的WPF纯XAML解决方案呢? 我调查了样式触发器,但语法并不是我自然而已。

谢谢!

2 个答案:

答案 0 :(得分:24)

将一些细节添加到Daniel's (slightly short) answer,因为一些所需的DataTrigger内容并不是真的很简单(如{x:Null}):

<TextBlock Text="{Binding MyTextProperty}">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding MyTextProperty}" Value="{x:Null}">
                    <Setter Property="Text" Value="Hey, the text should not be empty!"/>
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

顺便说一下:这完全是从内存中获取的,没有在VS或Blend 中检查它,所以请原谅那里是否有错误。但是,您应该能够自己解决它们。重要的是这个想法。祝你好运!

答案 1 :(得分:9)

您可以使用Converter进行此操作。使用IValueConverter创建类。在dataBinding之后使用此转换器

例如你的XAML

<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lib="clr-namespace:WpfApplication4"
    Title="Window1" Height="300" Width="300">

<Window.Resources>
    <lib:TextBlockDataConveter x:Key="DataConverter"/>
    <lib:TextBlockForegroundConverter x:Key="ColorConverter"/>
</Window.Resources>

<Grid>
    <TextBlock Text="{Binding Path=message, Converter ={StaticResource DataConverter}}" Foreground="{Binding message, Converter={StaticResource ColorConverter}}"/>
</Grid>

和你的转换器:

public class TextBlockDataConveter:IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {
            return "Error Message";
        }
        else
        {
            return value;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

class TextBlockForegroundConverter:IValueConverter
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {

            SolidColorBrush brush = new SolidColorBrush();
            brush.Color = Colors.Red;
            return brush;
        }
        else
        {
            SolidColorBrush brush = new SolidColorBrush();
            brush.Color = Colors.Black;
            return brush;

        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

它有效。检查一下。