我有一个usercontrol,用于编辑应用程序中的某些对象。
我最近来到一个实例,我想弹出一个新的对话框(窗口)来托管这个用户控件。
如何实例化新窗口并将需要从窗口设置的任何属性传递给usercontrol?
感谢您的时间。
答案 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)
你需要:
这里有一些看起来非常像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中绑定它们。