Search code examples
xamarinxamarin.ioscontainersxamarin.formsmaster-detail

Xamarin.Forms: Exchange view in container


I've created some pages

this.content1 = new DetailPage("ContentPage1");
this.content2 = new DetailPage("ContentPage2");

and I have defined a field

private View detailView;

with the following layout

Content = new StackLayout
{
    Padding = new Thickness(0, Device.OnPlatform<int>(20, 0, 0), 0, 0),
    Orientation = StackOrientation.Horizontal,
    Children = {
        buttonContainer,
        this.detailView,
    },
};

On a button click the detailView should be exchanged

private void Button1_Clicked(object sender, EventArgs e)
{
    this.detailView = this.content1.Content;
}

The click event is called, but the view isn't updated. Is this the wrong way to exchange a "subview" in a container? How is this done?


Solution

  • You need to remove the current detailView from the Children collection and then add your new view afterward. Simply swapping the value of detailView will not affect the visual UI.

    If I am understanding the context of your code snippets correctly, then this should resolve the problem in your Button1_Clicked handler:

    ((StackLayout) Content).Children.Remove(this.detailView);
    this.detailView = this.content1.Content;
    ((StackLayout) Content).Children.Add(this.detailView);