首页 > 解决方案 > Xamarin 形成 Fomed Label 跨度仅在绑定解决后可见

问题描述

我有一些带有格式化文本的标签,其中包含一些像这样的跨度

    <Label>
         <Label.FormattedText>
               <FormattedString>
                      <Span Text="Size: "/>
                      <Span FontAttributes="Bold" Text="{Binding Item.Size , Mode=OneWay}"/>
                      <Span FontAttributes="Bold" Text="{Binding Item.Unit, Mode=OneWay}"/>
               </FormattedString>
           </Label.FormattedText>
       </Label>

它看起来像这样:尺寸:32oz。 我希望只有在从数据库中解析上下文属性时才会出现“大小:”这个词

标签: c#xamldata-bindingxamarin.forms

解决方案


您可以使用转换器隐藏整个标签。我假设它Item.Size是一个字符串,但是在转换器中,您可以转换为正确的类型。这是一个示例

 public class OzViewConverter : IValueConverter
        {

            #region IValueConverter implementation

            public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                var test = value as string; //here you can change the cast, depending on type object you are Binding 
                if (!string.IsNullOrEmpty(test))  
                {
                    return true;
                }
                return false;
            }

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

            #endregion
        }

然后,在您的页面中

<ContentPage.Resources>
    <ResourceDictionary>
        <converter:OzViewConverter x:Key="OzViewConverter" />
    </ResourceDictionary>
</ContentPage.Resources>

 <Label IsVisible="{Binding Item.Unit, Converter={StaticResource OzViewConverter}}">
         <Label.FormattedText>
               <FormattedString>
                      <Span Text="Size: "/>
                      <Span FontAttributes="Bold" Text="{Binding Item.Size , Mode=OneWay}"/>
                      <Span FontAttributes="Bold" Text="{Binding Item.Unit, Mode=OneWay}"/>
               </FormattedString>
           </Label.FormattedText>
       </Label>

推荐阅读