绑定多个文本块属性

时间:2018-12-18 14:20:47

标签: xaml uwp textblock converters

在保存按钮上进行验证时,我有一个要求文本块应变为红色,粗体,下划线和字体应变大。

下面是我的xamlcode

<TextBlock  HorizontalAlignment="Right"
                            Foreground="{x:Bind Model.FirstNameError, Converter={StaticResource ErrorColorConverter}, Mode=OneWay}" 
                            FontStyle="{x:Bind Model.FirstNameError, Converter={StaticResource ErrorFontStyleConverter}, Mode=OneWay}"
                            FontSize="{x:Bind Model.FirstNameError, Converter={StaticResource ErrorFontSizeConverter}, Mode=OneWay}"                            
                    <Run Text="First Name" TextDecorations="{x:Bind Model.FirstNameError, Converter={StaticResource TextUnderlineConverter},Mode=OneWay}" />                    
                </TextBlock>

转换器代码:我为ErrorColorConverter,ErrorFontSizeConverter和TextUnderlineConverter创建了多个转换器,如下所示:

 public class ErrorFontStyleConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if ((bool)value)
                return  FontStyle.Italic;
            else
                return FontStyle.Normal;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }

    }

它完全按照我需要的方式工作,但是我需要一些建议以更好地完成此工作吗?我们是否有任何方法可以简化此过程enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用ConverterParameter并从单个转换器接收它们

 <TextBlock Foreground="{x:Bind FirstNameError,Mode=OneWay,Converter={StaticResource ErrorToFont},ConverterParameter=foreground}"
               FontStyle="{x:Bind FirstNameError,Mode=OneWay,Converter={StaticResource ErrorToFont},ConverterParameter=fontstyle}"
               FontWeight="{x:Bind FirstNameError,Mode=OneWay,Converter={StaticResource ErrorToFont},ConverterParameter=fontweight}">

//转换器

public class ErrorFontConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (parameter.ToString() == "fontstyle")
                return (bool)value ? Windows.UI.Text.FontStyle.Italic : Windows.UI.Text.FontStyle.Normal;
            else if (parameter.ToString() == "foreground")
                return (bool)value ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Blue);
            else
                return (bool)value ? FontWeights.Bold : FontWeights.Normal;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }

    }