gun
gun

Reputation: 27

show and hide UserControls based on button click

I have 3 UserControls and my MainWindow. In my UserControl3 I have two buttons (button1 & button2).

  1. I need to add the UserControl3 to my MainWindow when we start the application
  2. If I click button1, usercontrol1 should appear on my mainwindow, if i click button2, usercontrol2 should appear on my mainwindow.

How to do this? Have you an example of this?

Upvotes: 0

Views: 3108

Answers (1)

Ahmad N. Chatila
Ahmad N. Chatila

Reputation: 134

Right from your MainWindow.xaml, create two buttons at the bottom of the window, and add a Stack Panel at the center of the window.

... Or copy the following XAML markup in the <Grid> tag:

<Grid>
    <Button x:Name="UserControl1_Btn" Content="UserControl1" HorizontalAlignment="Left" Margin="10,289,0,10" Width="153"/>
    <Button x:Name="UserControl2_Btn" Content="UserControl2" Margin="354,0,10,10" Height="20" VerticalAlignment="Bottom"/>
    <StackPanel x:Name="StackPanelFixed_SP" Margin="10,10,10,47"/>
</Grid>

After that, create TWO User Controls from Solution Explorer by right-clicking the project name, then Add -> User Control... (Do that twice)

enter image description here

Add some content in the two User Controls anything you like, for this example I will use the background color so that you can tell whether if it was UserControl1 or UserControl2.

UserControl1 will be colored to BLACK

UserControl2 will be colored to RED

Add a click event to the first button and add the following lines of code:

enter image description here

    StackPanelFixed_SP.Children.Clear();
    UserControl1 UC1 = new UserControl1();
    StackPanelFixed_SP.Children.Add(UC1);
    UC1.Visibility = System.Windows.Visibility.Visible;

For the second button, add the following line of code:

    StackPanelFixed_SP.Children.Clear();
    UserControl2 UC2 = new UserControl2();
    StackPanelFixed_SP.Children.Add(UC2);
    UC2.Visibility = System.Windows.Visibility.Visible;

Finally, you will have a program that will start with TWO Buttons (one on the bottom-left, and the other on the bottom right) with a blank background. After clicking one of the buttons, you will get part of the UI being colored (I know it sounds stupid, but I'm trying to make a point for using the User Controls).

Upvotes: 2

Related Questions