开发者

WPF user controls

I am new to WPF, my problem is that I have a top menu as UserControl added in the main window a开发者_JAVA百科nd 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?


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


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

Good resources are:

  • NYC DevReady: MVVM - Session 1 (of 5) - Demystifying XAML
  • NYC DevReady: MVVM - Session 2 (of 5) - Programming with MVVM - Part 1
  • NYC DevReady: MVVM - Session 3 (of 5) - Programming with MVVM - Part 2

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜