将TextBlock的前景色绑定到局部变量

时间:2013-02-11 08:24:19

标签: .net wpf binding

我想将文本块的前景色绑定到局部变量。 如果变量没有值(= null),而前景颜色应该是黑色,如果变量不是null,则前景颜色应该是黑色或其他颜色。 是否有可能通过绑定来解决这个问题?

1 个答案:

答案 0 :(得分:0)

首先你可以使用值转换器来定义你的转换器

[ValueConversion (typeof(object), typeof(SolidColorBrush))]
public class ObjectToBrushConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return new SolidColorBrush(Colors.Black);
        return new SolidColorBrush(Colors.Red);
    }

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

然后在您的XAML文件中将转换器定义为资源

    <Window.Resources>
        <local:ObjectToBrushConverter x:Key="ObjectToBrushConverter"/>
    </Window.Resources>

然后绑定到您的属性并提供转换器

    <TextBox Name="textb" Text="Hello" Foreground="{Binding Path=MyObject,  Converter={StaticResource ResourceKey=ObjectToBrushConverter}}">

在价值转换器http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

上查看msdn

当然假设您在本例中将变量定义为公共属性和Object类型

相关问题