Reputation: 731
Let's say I got 2 ViewModels and 1 View
ViewModel_B
View_A
in ViewModel_A I got a costum property class PersonClass PersonClass has some fields
In View_A i'm binding some textboxes to the PersonClass property which is binded two way with datacontext ViewModel_A
In ViewModel_B in want to update the PersonClass property from code.
Whats the best way to do this cause like I'm working at the moment I'm making a new instance of ViewModel_A in ViewModel_B and than set the property PersonClass.
ViewModel_A viewModel_A = new ViewModel_A();
viewModel_A.PersonClass.Name = someString;
viewModel_A.PersonClass.Age = someString;
...
Like I'm doing it now I got 2 different instances of ViewModel_A, so my property PersonClass will never notice any changes...
Whats the best solution to solve this?
Upvotes: 0
Views: 63
Reputation: 11051
Your PersonClass must implement INotifyPropertyChanged and your View must get a viewmodel instance set as the DataContext. One nice way to handle with nested ViewModels, is to use ContentControls This is not necessary of course, but adds a nice way of customization, just switching the sub viewmodel allows changing parts of the UI.
class ViewModel_B
{
public ViewModel_A MySubViewModel{get;set;}
}
<DataTemplate x:Key="vmaTemplate" DataType="{x:Type ViewModel_A}">
<TextBlock Text="{Binding PersonClass.Name}"/>
</DataTemplate>
<Grid>
<ContentControl Content="{Binding MySubViewModel}"
ContentTemplate="{StaticTemplate vmaTemplate}"/>
</Grid>
This example assumes, that the Grid
has as the DataContext
an instance of ViewModel_B
.
Upvotes: 1