代码之家  ›  专栏  ›  技术社区  ›  Venkat

使用多个文本块属性绑定

  •  0
  • Venkat  · 技术社区  · 6 年前

    我有一个要求,在验证“保存”按钮时,文本块应变红、加粗、下划线和字体应变大。

    下面是我的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 回复  |  直到 6 年前
        1
  •  2
  •   Vignesh Kenneth Witham    6 年前

    你可以使用 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();
            }
    
        }
    
    推荐文章