将WPF数据网格中选定的ViewModel传递到新的TabItem MVVM
本文关键字:ViewModel MVVM TabItem 数据 WPF 数据网 网格 | 更新日期: 2023-09-27 18:29:55
我有一个选项卡控件,它在第一个选项卡中加载WPF数据网格。数据网格中的行是已填充MemberViewModels。当数据网格selectItem发生更改时,我已经成功地获得了所选的MemberViewModel,但我如何将其传递到RibbonViewModel,以便使用命令将其添加到TabItems集合?RibbonViewModel是我的Ribbon的ViewModel。在功能区上有一个按钮,可以将新的MemberViewModel添加到选项卡ItemsCollection中,这很好。但是,我想将数据网格中选定的MemberViewModel添加为新的选项卡项。
RibbonViewModel中的代码(命令),它将新的MemberViewModel添加到TabItemsCollection
private void AddSelectedMemberTabItem(object notUsed)
{
_tabViewModel.TabItems.Add(new MemberViewModel{ Header = "Member" }); // OK, this works fine
_tabViewModel.TabItems.Add(SelectedMemberViewModel); // this doesnt work, DP SelectedMemberViewModel is never filled, don't know how to retrieve it from the selected datagrid item.
_addOverview.RaiseCanExecuteChanged();
}
从所选数据网格检索所选MemberViewModel的代码(在OverviewViewModel中):
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(MemberViewModel), typeof(OverviewViewModel), new UIPropertyMetadata(OnSelectedMemberPropertyChanged));
public MemberViewModel SelectedItem
{
get { return (MemberViewModel)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
private static void OnSelectedMemberPropertyChanged(DependencyObject m, DependencyPropertyChangedEventArgs args)
{
var selectedMember = m.GetValue(SelectedItemProperty) as MemberViewModel;
_ribbonViewModel.SelectedMemberViewModel = selectedMember; // error: cannot access non-static field (_ribbonViewModel) in static contect
}
如何从OverviewViewModel上的OnSelectedMemberPropertyChanged方法填充_ribbonViewModel.SelectedMemberViewModel?还是我做错了?
这是我必须要做的一种方式,通过这种方式,我可以将所选的MemberViewModel从DataGrid传递给其他变量。
private static void OnSelectedMemberPropertyChanged(DependencyObject m, DependencyPropertyChangedEventArgs args)
{
var b = m as OverviewViewModel;
if (b == null)
return;
var selectedMember = m.GetValue(SelectedItemProperty) as MemberViewModel;
b.selectedMemberChanged(selectedMember);
}