切换切换时隐藏数据单元格中的行

时间:2018-12-12 19:29:07

标签: listview xamarin mvvm xamarin.forms

这是我的xaml模板文件:

    <Switch  IsToggled="{Binding ShowSubItems}" Grid.Row = "0" Grid.Column = "1" HorizontalOptions = "Start" Margin = "10,8,8,0"></Switch>

其次:

      <ListView x:Name="lvItemSigns" HasUnevenRows="True" SeparatorVisibility="Default" SeparatorColor="Gray" Margin =" 8">

Im将数据单元格绑定到此列表,如下所示:

                lvItemSigns.ItemTemplate = new DataTemplate(typeof(DataCell));

        class DataCell : ViewCell{
public DataCell()
        {
            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition { Height =  GridLength.Auto});
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            label = new Label();
            label.TextColor = Color.Black;
            label.SetBinding(Label.TextProperty, "SubItemCode");
            label.Margin = 4;
            grid.Children.Add(label, 1, 3);

            label = new Label();
            label.TextColor = Color.Black;
            label.SetBinding(Label.TextProperty, "SubItemDescription");
            label.Margin = 4;

            label.SetBinding(Label.IsVisibleProperty, new Binding("SubItemDescription", BindingMode.Default, new BooleanConverter()));

            grid.Children.Add(label, 1, 4);
}

切换切换后如何从列表的每个数据单元中隐藏这两个标签。

谢谢

1 个答案:

答案 0 :(得分:0)

设置IsVisibleProperty时,绑定属性不应该是“ ShowSubItems”吗?

代码将是

label.SetBinding(Label.IsVisibleProperty, new Binding("ShowSubItems", BindingMode.Default, new BooleanConverter()));

另外,请确保已通知“ ShowSubItems”属性中更改的属性。例如,

 private bool showSubItems;
    public bool ShowSubItems
    {
        get { return showSubItems; }
        set { showSubItems = value; OnPropertyChanged(); }
    }

转换器代码也应该是

public class BooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool))
            throw new InvalidOperationException("The target must be a boolean");

        return !(bool)value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Optional: throw new NotSupportedException();
        return null;
    }
}