开发者

WPF window hosting usercontrol

开发者 https://www.devze.com 2022-12-19 20:10 出处:网络
I have a usercontrol that I use to edit some objects in my application. I have recently come to an instance where I want to pop up a new dialog (window) which will host this usercontrol.

I have a usercontrol that I use to edit some objects in my application.

I have recently come to an instance where I want to pop up a new dialog (window) which will host this usercontrol.

How do I instant开发者_开发技巧iate the new window and pass any properties that need to be set from the window to the usercontrol?

Thanks for your time.


You can simply set the content of your new window to your user control. In code, this would be something like this:

...

MyUserControl userControl = new MyUserControl();

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

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

...


You need to:

  1. Create some public properties on your dialog Window to pass in the values
  2. Bind your UserControl to those public properties in your dialog Window
  3. Show your dialog Window as dialog when needed
  4. (optional) retrieve values from the window that are two-way bound to your user control

Here's some pseudocode that looks remarkably like C# and XAML:

How to show a window as a dialog:

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

and the source

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

and the 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>

you'd do the same thing in your UserControl as you've done in your window to create public properties and then bind to them within the xaml.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号