WPF窗口托管usercontrol

时间:2010-02-05 16:05:44

标签: wpf user-controls window

我有一个usercontrol,用于编辑应用程序中的某些对象。

我最近来到一个实例,我想弹出一个新的对话框(窗口)来托管这个用户控件。

如何实例化新窗口并将需要从窗口设置的任何属性传递给usercontrol?

感谢您的时间。

2 个答案:

答案 0 :(得分:14)

您只需将新窗口的内容设置为用户控件即可。在代码中,这将是这样的:

...

MyUserControl userControl = new MyUserControl();

//... set up bindings, etc (probably set up in user control xaml) ...

Window newWindow = new Window();
newWindow.Content = userControl;
newWindow.Show();

...

答案 1 :(得分:1)

你需要:

  1. 在对话框窗口中创建一些公共属性以传递值
  2. 将UserControl绑定到对话框窗口
  3. 中的公共属性
  4. 在需要时将对话框窗口显示为对话框
  5. (可选)从窗口中检索与用户控件双向绑定的值
  6. 这里有一些看起来非常像C#和XAML的伪代码:

    如何将窗口显示为对话框:

    var myUserControlDialog d = new MyUserControlDialog();
    d.NeededValueOne = "hurr";
    d.NeededValueTwo = "durr";
    d.ShowDialog();
    

    和来源

    public class MyUserControlDialog : Window
    {
      // you need to create these as DependencyProperties
      public string NeededValueOne {get;set;}
      public string NeededValueTwo {get;set;}
    }
    

    和xaml

    <Window x:Class="MyUserControlDialog" xmlns:user="MyAssembly.UserControls">
     <!-- ... -->
      <user:MyUserControl
        NeededValueOne="{Binding NeededValueOne, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
        NeededValueTwo="{Binding NeededValueTwo, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
    </Window>
    

    你在UserControl中做同样的事情就像你在窗口中做的那样创建公共属性然后在xaml中绑定它们。