Xamarin.forms - 自定义 ViewCell 中的 BoxView

Xamarin.forms - BoxView in Customized ViewCell

我想为列表的最后一个元素将 BoxView 的 VisibleProperty 设置为 false,该元素在包含堆栈布局(网格+框视图)的视单元中定义。有什么方法可以让它为 false,这样最后一个元素就不会包含 boxview 分隔线了吗?

解法:

您可以在您的 viewModel 中添加一个 bool 属性 isShow 并使用此 属性 来控制 boxView 是否可见。

public class MyViewModel
    {
        //use this property to control whether the boxView is visible
        public bool isShow { get; set; }
    }

然后将此 属性 绑定到自定义单元格中的 boxView 通过 boxOne.SetBinding(BoxView.IsVisibleProperty, new Binding("isShow")):

public CustomCell()
    {
        //instantiate each of our views

        var grid = new Grid();
        var horizontalLayout = grid;
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

        var boxOne = new BoxView { BackgroundColor = Color.Purple };
        var boxTwo = new BoxView { BackgroundColor = Color.AliceBlue };    
        grid.Children.Add(boxOne, 0, 0);        
        grid.Children.Add(boxTwo, 1, 1);

        //Binding here
        boxOne.SetBinding(BoxView.IsVisibleProperty, new Binding("isShow"));

        View = horizontalLayout;                 
     }

最后,当你创建MyViewModel的新实例时,你可以设置isShow 属性 true/false来控制boxView是否是在您的单元格中可见。

    public MainViewCode()
    {
        myCollection = new ObservableCollection<MyViewModel>();
        ListView lstView = new ListView();  
        lstView.ItemTemplate = new DataTemplate(typeof(CustomCell));

        myCollection.Add(new MyViewModel { isShow = true });
        myCollection.Add(new MyViewModel { isShow = false });
        lstView.ItemsSource = myCollection;

        Content = lstView;
    }