c# - 将命令绑定(bind)到子 ViewModel

标签 c# wpf mvvm commandbinding

我正在尝试将命令从功能区绑定(bind)到内容控件。

我的观点是这样的:

  <Window.Resources>
    <DataTemplate DataType="{x:Type VM:CityViewModel}">
        <Views:EditorView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type VM:CountryViewModel}">
      <Views:EditorView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type VM:SomeOtherViewModel}">
      <Views:SomeOtherView />
    </DataTemplate>
  </Window.Resources>
 <DockPanel>
    <Fluent:Ribbon x:Name="MainRibbon"
                   AutomaticStateManagement="True"
                   DockPanel.Dock="Top">
      <Fluent:RibbonTabItem Header=SomeHeader>
      <Fluent:RibbonGroupBox Header="Actions">
       <Fluent:Button Fluent:RibbonAttachedProperties.RibbonSizeDefinition="Middle,Small"
                      Header="New"
                      Command = "{Binding NewCommand}"
                      CommandTarget="{Binding ElementName=SubView}"/>
       <Fluent:Button Fluent:RibbonAttachedProperties.RibbonSizeDefinition="Middle,Small" Header="Save"
                      Command = "{Binding SaveCommand}"
                      CommandTarget="{Binding ElementName=SubView}"/>
      </Fluent:RibbonGroupBox>
     </Fluent:RibbonTabItem>
   </Fluent:Ribbon>           
  <ContentControl Name="SubView" Content="{Binding CurentSubView}" />
 </DockPanel>

MainViewModel 从 IOC 设置 CurrentSubView:
CurentSubView = ViewModelFactory.Create<SomeViewModel>();
CityViewModelCountryViewModel来自 EditorViewModel<T> 并分享已发布到 EditorViewModel<T> 的基本操作基类
 public RelayCommand NewCommand { get; private set; }
 public RelayCommand SaveCommand { get; private set; }

ETC....

我的问题是如何将命令从 subview 模型公开到功能区?

由于第一个 View 模型 CurrentSubView 没有实现这些命令,所以我得到“BindingExpression 路径错误:在'object'''MainViewModel'上找不到'NewCommand'属性”.....

我设法通过我添加的 MainViewModel 中的一些代码绑定(bind)命令:
 private RelayCommand m_newCommand;
 public RelayCommand NewCommand
   {
     get { return m_newCommand; }
   }

  if (typeof(IEditorViewModel).IsInstanceOfType(CurentSubView))
  {
    m_newCommand = ((IEditorViewModel)CurentSubView).NewCommand;
    RaisePropertyChanged(() => NewCommand);
  }
  else
  {
    m_newCommand = null;
  }


但仍然开放以获得更优雅的建议;)

最佳答案

所以它很简单。<fluent:RibbonTabItem/>有吗DataContext所以只需要做:

<fluent:RibbonTabItem Name="SomeTab" DataContext="{Binding CurrentViewModel}" Header="SomeTab">

关于c# - 将命令绑定(bind)到子 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796181/

相关文章:

c# - 如何在 C# 中将递归对象转换为集合?

c# - 选择节点 Linq to Xml C#

c# - 在 silverlight 项目中引用 asp.net c# 类/方法

c# - 序列化 NodaTime JSON

c# - 如果我想在 WPF 和 UWP 项目中使用 IValueConverter,最佳实践是什么

WPF 将 IsEnabled 绑定(bind)到列表框 SelectedItem

c# - 如何动态地将控件添加到另一个类中的WrapPanel?

WPF - 将 RadioButton 样式设置为 ToggleButton 有效,但在 VS 中显示错误

c# - 根据当前上下文显示RibbonTab的内容

MVVM 组合框绑定(bind)