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 instantiate 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:
- Create some public properties on your dialog Window to pass in the values
- Bind your UserControl to those public properties in your dialog Window
- Show your dialog Window as dialog when needed
- (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.