2010-02-05 72 views
7

我有一个用户控件,我用它来编辑我的应用程序中的一些对象。WPF窗口托管usercontrol

我最近来到一个实例,我想弹出一个新的对话框(窗口),将承载此用户控件。

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

谢谢你的时间。

+0

您的用户控件是否通常绑定到您正在编辑的对象?更多信息可能会有用。至于在新窗口中实例化的选项......你可以尝试一个弹出窗口或一个新的窗口,它将你的usercontrol作为一个子窗口,并且在你设置了属性或绑定了属性值之后调用.Show()方法到你正在编辑的内容。 – Scott 2010-02-05 16:12:18

回答

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(); 

... 
+2

我喜欢它,当它那么简单和直接 – 2012-07-14 09:00:18

1

您需要:

  1. 创建你的对话窗口中一些公共属性的值
  2. 绑定你的用户控件传递给那些公共属性在你的对话窗口
  3. 显示你的对话窗口当需要时作为对话框
  4. (可选)从双向绑定到用户控件的窗口中检索值

下面是一些伪代码,看起来非常像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中绑定它们一样。

相关问题