Show a usercontrol in MainWindow

111 views Asked by At

I my project I have the MainForm with 2 UserControls. The UserControl1 have a button that makes the UserControl2 Visible.

Here's what I did:

USERCONTROL1

    private void Button1_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        MainWindow mw = new MainWindow();
        mw.CallMethod();
    }

MAINWINDOW

    public void CallMethod()
    {
        USERCONTROL2 UC2 = new USERCONTROL2();
        UC2.Visibility = Visibility.Visible;
        grid.Children.Add(UC2);

    }

...but when I click the UserControl1's button, nothing is happening.

2

There are 2 answers

0
Robert J. On BEST ANSWER

Declare in your background code following:

Private Visibility _vis_UC_2;
Public Visibility vis_UC2
{
get
{
   return _vis_UC2;
}
set
{
   _vis_UC2 = value;
   OnPropertyChanged("vis_UC2");
}
}

Don't forget to add INotifyPropertyChanged to your class

Then you bind your UserControl's visibility to vis_UC2.

In Constructor set starting visibility such as following

Public Void MainWindow()
{
   InitializeCompotenents();
   vis_UC2 = Visibility.Collapsed;
}

and finally under your button click you only say the following:

vis_UC2 = Visibility.Visible;
0
AudioBubble On

Add in your Form a panel and do this:

UserControl1 u1 = new UserControl1();
UserControl2 u2 = new UserControl2();

// When you want UserControl1.
u2.Hide();
u1.Show();
u1.Dock = DockStyle.Fill;
panel1.Controls.Add(u1);

// When you want UserControl2.
u1.Hide();
u2.Show();
u2.Dock = DockStyle.Fill;
panel1.Controls.Add(u2);