Xamarin形成Fomated Label跨度,仅在解决绑定后可见

时间:2019-01-21 17:38:33

标签: c# xaml data-binding xamarin.forms

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

    <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>

它看起来像这样:大小: 32盎司。我希望仅在从数据库解析上下文属性时才出现“大小:”一词

1 个答案:

答案 0 :(得分:1)

您可以使用转换器来隐藏整个标签。我假设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>