Smallestearth Smallestearth - 1 month ago 8
C# Question

Pass the value from View to the Mainwindow when the View is closed

I have made a Usercontrol based on MVVM. A window(e.g. MainWindow.xaml) calls this Usercontrol, the View of this Usercontrol has a treeview with nodes, child nodes and buttons ('ok', etc...). The user selects a node in the treeview and press the "ok" button on the View. I could read the selected nodes of the treeview in the View.xaml.cs. I have created dependency properties in View.xaml.cs to save the selected treeview item. In the mainwindow.xaml.cs, I am instantiating my usercontrol and calling the dependency property e.g. usercontrol.value where value is the dependency property in the View.
The overall idea is when user selects the treeview node and press ok, the view should be close and the value of the selected treeview item is paased to the Window.

The problem is when I close the view the value of the dependency property get lost and null is returned to the Window

I am new to WPF.

Window.xaml

<Grid>
<view:SystemExplorerView x:Name="MyView"></view:SystemExplorerView>
</Grid>


Window.xaml.cs

public object m_myValue;
public object myValue {
get { return m_myValue; }
set
{
m_myValue = value;
OnPropertyChanged("myValue");
}
}
public Window1()
{
InitializeComponent();
myValue = MyView.Value;
}


View.xaml.cs

public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(object), typeof(SystemExplorerView),
new PropertyMetadata(null));
public SystemExplorerView()
{
InitializeComponent();
}
public object Value
{
get { return (object)GetValue(ValueProperty); }
set
{
SetValue(ValueProperty, value);

}
}
private void OKbtnclk(object sender, RoutedEventArgs e)
{
Value = myTreeView.SelectedItem;
Window.GetWindow(this).Close();
}

Answer Source

You may access the property in a Closing event handler:

<Window ... Closing="Window_Closing">
    ...
</Window>

Code behind:

private void Window_Closing(object sender, CancelEventArgs e)
{
    myValue = MyView.Value;
}