Reputation: 8273
I have a scenario that Main-window has content control i switch user control of particular view through it and have View-Models respectively
In one of my User-Control has another user-control in it. Both have a View-Model
<UserControl DataContext="ViewModel1">
<Grid>
<ListView ItemsSource="{Binding TimeSlotCollection}" <!--This Collection is in ViewModel 1-->
">
</ListView>
<UserControl DataContext="ViewModel2">
<DataGrid x:Name="DataGrid"
CanUserAddRows="True"
ItemsSource="{Binding TimeSlotCollection,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"/> <!--This Collection is in ViewModel 2-->
</Grid>
</UserControl>
I want Notify the View-model 1 Collection when View-model 2 Collection is Changed
MyViewModel 1
private ObservableCollection<AttendanceTimeSlotModel> _timeslotCollection;
public ObservableCollection<AttendanceTimeSlotModel> TimeSlotCollection
{
get { return _timeslotCollection; }
set
{
Set(TimeSlotCollectionPropertyName, ref _timeslotCollection, value);
}
}
public const string EmployeesCollectionPropertyName = "Employees";
private ObservableCollection<EmployeeModel> _employees;
public ObservableCollection<EmployeeModel> Employees
{
get { return _employees; }
set
{
Set(EmployeesCollectionPropertyName, ref _employees, value);
}
}
public const string IsBusyPropertyName = "IsBusy";
private bool _isBusy = false;
public bool IsBusy
{
get
{
return _isBusy;
}
set
{
Set(IsBusyPropertyName, ref _isBusy, value);
}
}
MyViewModel 2
public const string AttendanceTimeSlotCollectionPropertyName = "TimeSlotCollection";
private ObservableCollection<AttendanceTimeSlotModel> _timeSlotCollection = null;
public ObservableCollection<AttendanceTimeSlotModel> TimeSlotCollection
{
get
{
return _timeSlotCollection;
}
set
{
Set(AttendanceTimeSlotCollectionPropertyName, ref _timeSlotCollection, value);
}
}
/// What i trying
public void AddNewTimeSlot(AttendanceTimeSlotModel timeSlot)
{
_designdataService.InsertTimeSlot(timeSlot);
var Vm = SimpleIoc.Default.GetInstance<ViewModels.AssignTimeSlotViewModel>();
RaisePropertyChanged(Vm.TimeSlotCollection);
}
What i'm trying to achieve when my collection inside View-model 2 is updated i want to notify in View-model 1.
Upvotes: 0
Views: 627
Reputation: 69959
When using MVVM, I like to use just one view model to one view. If you simply take your inner UserControl
to be part of its parent UserControl
, then you'll only need one view model. Try re-arranging your code like this:
<UserControl DataContext="ViewModel1">
<Grid>
<ListView ItemsSource="{Binding TimeSlotCollection}" />
<UserControl DataContext="{Binding TimeSlotCollection}">
...
<!-- Then inside the inner control -->
<DataGrid x:Name="DataGrid" ItemsSource="{Binding}" ... />
...
</UserControl>
</Grid>
</UserControl>
In this way, you just have to manage the one collection in the one view model and most of your problems will just disappear.
Upvotes: 2