Notify Collection在视图模型中发生了更改
本文关键字:发生了 模型 Collection 视图 Notify | 更新日期: 2023-09-27 17:59:17
我有一个场景,主窗口有内容控制,我通过它切换特定视图的用户控制,并分别有视图模型
在我的一个用户控件中有另一个用户控制器。两者都有一个视图模型
<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>
我想在视图模型2集合更改时通知视图模型1集合
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);
}
当我在视图模型2中的集合更新时,我想在视图模型1中通知我想要实现的目标。
使用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>
这样,您只需要在一个视图模型中管理一个集合,大多数问题就会消失。