将选定的ViewModel从WPF数据网格传递到新的TabItem MVVM

时间:2012-04-04 13:01:41

标签: c# wpf mvvm

我有一个tabcontrol,它在第一个标签中加载一个WPF数据网格。数据网格中的行是 填充了MemberViewModels。 我已经设法在datagrids selectItem被更改时获取所选的MemberViewModel,但是我如何将它传递给我的RibbonViewModel,我想用命令将它添加到TabItems集合? RibbonViewModel是我的功能区的ViewModel。在该功能区上有一个按钮,它将新的MemberViewModel添加到tabItemsCollection,这很好。但是,我想从我的数据网格中添加所选的MemberViewModel,以作为新的tabitem添加。

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();
}

从所选datagriditem(在OverviewViewModel中)检索所选MemberViewModel的代码:

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?或者我是否采取了错误的方式?

1 个答案:

答案 0 :(得分:0)

这是我必须这样做的方式,这样我就可以将选定的MemberViewModel从DataGrid传递给另一个var。

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);
}