views:

43

answers:

2

I've been having trouble with some databinding with WPF. I have a class to hold various data. I want the data it holds to be binded to Text Boxes in a different window. Everything I've found reccomends this:

<Grid.Resources>
    <c:PropertyModel x:Key="propMod" />
</Grid.Resources>
<Grid.DataContext>
    <Binding Source="{StaticResource propMod}"/>
</Grid.DataContext>

The problem with this is it's instantiated somewhere and I have no way to get to this 'propMod'. I'd like to change some of propMod's properties from code.

The other method I've tried is to create an instance in the code-behind, eg

PropertyModel propMod = new PropertyModel();

But I can't get WPF to bind to this, despite the documentation claiming that {Binding propMod.PropA} should work.

Thanks

+1  A: 

The key thing you want is to set the DataContext (of your Window, Grid, etc.) to an instance of your PropertyModel.

Often, I will do this in the code-behind of the View like the following:

var viewModel = new SomeAwesomeViewModel();
DataContext = viewModel;

That can be in the constructor, or in an event handler for the Loaded event of the Window.

If you want to be able to manipulate some properties of the ViewModel from some other code, then maybe you should instantiate the ViewModel somewhere else (e.g., inside another ViewModel which knows what modifications need to be done), then pass the instantiated and modified ViewModel to the View to use. I've done something similar to this via an event and a custom EventArgs parameter that contained the ViewModel.

Eric
Thanks Eric, this seems like the best way to do things, as having the XAML instantiate the model is a bit weird.
Mason Blier
+1  A: 

You should be able to use the code approach - but you'll need to explicitly set the Grid's DataContext to your newly instanced "propMod" variable.

If you want to use the first approach, you can access the resource from code. You'll need to find the grid, then do:

Grid grid = MethodToGetTheGridInstance();
PropertyModel propMod = (PropertyModel)grid.FindResource("propMod");

For details on getting resources from code, see MSDN.

Reed Copsey
Thanks for a solution.
Mason Blier