5

在我的应用程序中,我使用Xamarin.Forms AbsoluteLayout. 我有一个自定义菜单栏。当我点击一个菜单按钮时,我的主要内容(a ViewAbsoluteLayout应该被替换。

到目前为止,我只能通过添加一个新子项并使用 and 设置其布局边界来实现这Children.Add()一点SetLayBounds()。但是通过这种方式,我添加了越来越多的孩子并且永远不会删除它们。

将孩子从AbsoluteLayout.

4

2 回答 2

11

.Children实现IList<View>(和ICollection<View>,,, ) IEnumerable<View>Ienumerable以便您可以在最方便的时候使用:

  • layout.Children.RemoveAt (position),
  • layout.Children.Remove (view),
  • layout.Children.Clear ()

如果你知道你的视图的索引.Children,你也可以替换元素:

layout.Children[position] = new MyView ();

但这为您提供的选项比Children.Add (...)覆盖更少,您必须使用SetLayoutBoundsand SetLayoutFlags

于 2014-09-05T11:58:49.037 回答
0

尝试使用 AbsoluteLayout.Children 集合的 RemoveAt 方法的以下代码段。

或者,如果您有变量引用,您可以使用 Remove(View) 方法。

        StackLayout objStackLayout = new StackLayout()
        {
        };
        //
        AbsoluteLayout objAbsoluteLayout = new AbsoluteLayout()            
        {
        };
        //
        BoxView objBox1 = new BoxView()
        {
            Color = Color.Red,
            WidthRequest = 50,
            HeightRequest = 50,
        };
        objAbsoluteLayout.Children.Add(objBox1, new Point(100,100));
        System.Diagnostics.Debug.WriteLine("Children Count : " + objAbsoluteLayout.Children.Count);
        //
        BoxView objBox2 = new BoxView()
        {
            Color = Color.Green,
            WidthRequest = 50,
            HeightRequest = 50,
        };
        objAbsoluteLayout.Children.Add(objBox2, new Point(200, 200));
        System.Diagnostics.Debug.WriteLine("Children Count : " + objAbsoluteLayout.Children.Count);
        //
        Button objButton1 = new Button()
        {
            Text = "Remove First Child"
        };
        objButton1.Clicked += ((o2, e2) =>
            {
                if (objAbsoluteLayout.Children.Count > 0)
                {
                    // To Remove a View at a specific index use:-
                    objAbsoluteLayout.Children.RemoveAt(0);
                    //
                    DisplayAlert("Children Count", objAbsoluteLayout.Children.Count.ToString(), "OK");
                }
                else
                {
                    DisplayAlert("Invalid", "There are no more children that can be removed", "OK");
                }
            });

        //
        objStackLayout.Children.Add(objAbsoluteLayout);
        objStackLayout.Children.Add(objButton1);
于 2014-09-05T12:06:55.170 回答