WPF窗口托管用户控件

7

我有一个用户控件,用于编辑我的应用程序中的一些对象。

最近遇到了这样的情况:我想弹出一个新的对话框(窗口),该窗口将托管此用户控件。

如何实例化新窗口并将需要从窗口设置到用户控件的任何属性传递?

感谢您的时间。


你的用户控件通常绑定到你正在编辑的对象吗?更多信息可能会有用。至于在新窗口中实例化的选项...你可以尝试弹出窗口或一个新窗口,其中包含你的用户控件作为子控件,并在设置属性或绑定值后调用.Show()方法。 - Scott
2个回答

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

...

3
我喜欢事情变得简单明了。 - Mehdi LAMRANI

1
您需要:
  1. 在对话框窗口上创建一些公共属性以传递值
  2. 在对话框窗口中将您的UserControl绑定到这些公共属性
  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中绑定它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接