1

I am new to WPF, my problem is that I have a top menu as UserControl added in the main window and the main window is split into three columns: in the right most column I have a DockPanel, now my problem is that I don't know how to add another control in that right column when I click on the top menu item.

Some code, to illustrate my attempt:

public partial class TopMenu : UserControl
{
    private void menuItem_Click(object sender, RoutedEventArgs e)
    {
        SecondControl ctrl = new SecondControl();
        Window1 winMain = new Window1();

        winMain.dp3.Children.Add(ctrl ); // dp3 is the dock panel in the right column of
    }
}

Now, what should I do to display that control on window1?

DanielB
  • 19,910
  • 2
  • 44
  • 50
user765573
  • 21
  • 6

2 Answers2

0

The problem is that you're adding the control to the DockPanel of a new instance of a Window1 window. You will need to 'find' the instance of the Window1 type in which the your TopMenu control is embedded.

Using the code from here we can find the top-level control, your window, and then add the controls to that instance:

private void menuItem_Click(object sender, RoutedEventArgs e)
{
    var topLevelControl = GetTopLevelControl(this);
    if (topLevelControl != null && topLevelControl is Window1)
    {
        var currentWindow = topLevelControl as Window1;
        SecondControl ctrl = new SecondControl();   
        currentWindow.dp3.Children.Add(ctrl ); 
    }
}

DependencyObject GetTopLevelControl(DependencyObject control)  
{
    DependencyObject tmp = control;
    DependencyObject parent = null;
    while((tmp = VisualTreeHelper.GetParent(tmp)) != null)
    {
        parent = tmp;
    }
    return parent;
}
Community
  • 1
  • 1
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • No worries; though it seems we have a disgruntled, mystery downvoter - to them I ask that they please elaborate on their reasons _why_, particularly since the answer is correct and clearly aided to OP (evident prior to the downvote.) – Grant Thomas Jun 14 '11 at 11:12
-1

Because you are new to WPF I recommend that you invest some time learning MVVM, binding, INotifyPropertyChanged interface etc.

Good resources are:

You could solve your problem in multiple ways. For example, you could put ContentControl to the right column where you want to show your SecondControl. Now, when you want to show your SecondControl just fill Content property of the ContentControl with the SecondControl

Robert Vuković
  • 4,677
  • 6
  • 31
  • 47