我有一个场景,主窗口有内容控制我通过它切换特定视图的用户控件,并分别有View-Models
在我的一个用户控件中有另一个用户控件。两者都有视图模型
<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>
我想在View-model 2 Collection更改时通知View-model 1 Collection
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);
}
当我在View-model 2中更新我的收藏时,我想要在View-model 1中通知我想要实现的目标。
答案 0 :(得分:2)
使用MVVM时,我只想在一个视图中使用一个视图模型。如果您只是将内部UserControl
作为其父UserControl
的一部分,那么您只需要一个视图模型。尝试重新安排您的代码:
<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>
通过这种方式,您只需在一个视图模型中管理一个集合,并且大多数您的问题就会消失。