Xamarin表单自定义ViewCell,如果空的话,不要添加到网格中?

时间:2016-06-03 09:55:19

标签: c# xamarin xamarin.forms

我创建了一个自定义视单元,我将文本绑定到标签然后将其插入网格中。但是,如果我传递给Viewcell的文本为空,如何避免空行?这只是一些代码,但如果文本为空,是否存在一些我缺少的绑定?

public RouteElementsCustomCell()
{
    Label NameLbl = new Label()
    {
        TextColor = Color.Black,
        HorizontalTextAlignment = TextAlignment.Center,
        FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
    };
    NameLbl.SetBinding(Label.TextProperty, "StopName");

    Grid grid = new Grid()
    {
        Padding = 10,
        RowDefinitions =
        {
            new RowDefinition
            {
                Height = GridLength.Auto
            },
        }
    };
    grid.Children.Add(NameLbl,0,1,0,1);
}

2 个答案:

答案 0 :(得分:0)

好吧,这就是我在@irreal帮助下解决这个问题的方法。

  

这可能会为您的viewmodel带来不必要的复杂性。考虑使用将字符串转换为布尔值的xaml值转换器。然后你就可以绑定IsVisible =“{Binding StopName,Converter = {}}”它非常有用,可以让你做很多事情,包括基于字符串的控件可见性不是空或空 - @irreal

将Label.IsVisibleProperty添加到标签,然后使用IValueConverter检查字符串是否为空,null或空格。

<强>标签

Label NameLbl = new Label()
{
    TextColor = Color.Black,
    HorizontalTextAlignment = TextAlignment.Center,
    VerticalOptions = LayoutOptions.Start,
    FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
};
NameLbl.SetBinding(Label.TextProperty, "StopName");
NameLbl.SetBinding(Label.IsVisibleProperty, "StopName",BindingMode.Default,new StringToBoolConverter(), null);

<强> ValueConverter

public class StringToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string valueAsString = value.ToString();
        if (string.IsNullOrWhiteSpace(valueAsString))
        {
            return false;
        }
        else
        {
            return true;
        }

    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

答案 1 :(得分:-1)

我要做的是向我的对象添加一个公共属性:

public bool ShowItem { get{return !string.IsNullOrEmpty(StopName)};}

然后将IsVisibleProperty绑定到ShowItem