I want to use the SaveFileDialog in the code behind to write a file using data that is contained in the ViewModel. The XAML class I am working with is populated by a selection made in a listbox in the parent class:
<Views:ChildView DataContext="{Binding Path=SelectedItem, ElementName=childrenListbox}"></Views:ChildView >
Then, within the ChildView XAML file I am able to freely access properties/methods of the ChildViewModel as expected. However, I don’t know how to access them from the code behind. I have a “Save File” button
<Button Content="Save File" Click="Button_Click"></Button>
whose event is handled in the code behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
//Here I would like to call the SaveFile function in ChildViewModel
}
}
I have tried looking through all the available properties but I cannot find a way to access the instance of ChildViewModel that I am working with. This question might have a simple solution, but I am not familiar with using the code-behind because I am making my first guild and I have been using the MVVM approach. I will strongly appreciate any answers that help me find a working solution. Also, please feel free to criticize me for using the code behind with MVVM if there is a way to avoid it and get a SaveFileDialog by only using XAML (then I could easily do the file saving within the ModelView).
Not sure where you are setting your ViewModel because you did not show the code for it, but usually it sits on the
DataContextproperty of your root element.So you could just cast it like that.