【问题标题】:WPF window hosting usercontrolWPF 窗口托管用户控件
【发布时间】:2010-02-05 16:05:44
【问题描述】:

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

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

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

感谢您的宝贵时间。

【问题讨论】:

  • 您的用户控件是否通常绑定到您正在编辑的对象?更多信息可能有用。至于在新窗口中实例化的选项......您可以尝试一个弹出窗口或一个将您的用户控件作为子控件的新窗口,并在设置属性或绑定值后调用 .Show() 方法到您正在编辑的内容。

标签: wpf user-controls window


【解决方案1】:

您可以简单地将新窗口的内容设置为您的用户控件。在代码中,这将是这样的:

...

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】:

你需要:

  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 中绑定到它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2018-01-16
    • 1970-01-01
    • 2012-03-27
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多