Il Hwan  Yu
Il Hwan Yu

Reputation: 13

How do I switch the WPF UserControl?

I want to change to UserControl2 when pressed button in UserControl1 attatched to the MainWindow.

MainWindow.xaml

<Viewbox Grid.Row="1" HorizontalAlignment="Center">
        <Grid>
            <local:A x:Name="a" Margin="0,0" Width="1200" /> <--UserControl1
            <local:B x:Name="b" Margin="0,0" Width="1200" /> <--UserControl2
        </Grid>
    </Viewbox>

MainWindow.xaml.cs

public MainWindow()
    {
        this.Closed += this.WindowClosed;
        this.InitializeComponent();

        this.a.Visibility = Visibility.Visible;
        this.b.Visibility = Visibility.Hidden;
    }

If button clicked than

this.a.Visibility = Visibility.Hidden; 
this.b.Visibility = Visibility.Visible;

How can I achieve this?

Upvotes: 1

Views: 103

Answers (1)

Chamika Sandamal
Chamika Sandamal

Reputation: 24322

Put following code in your button click event

Window w = Window.GetWindow(this);
if(null != w)
{
    ((UserControl)w.FindName("a")).Visibility = Visibility.Hidden;
    ((UserControl)w.FindName("b")).Visibility = Visibility.Visible;
}

Upvotes: 1

Related Questions