Search code examples
c#wpfuser-controlsexpression-blend-4

Show a usercontrol in MainWindow


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.


Solution

  • 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;