【发布时间】:2013-11-05 18:32:55
【问题描述】:
我正在尝试将命令从功能区绑定到内容控件。
我的视图如下所示:
<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>();
CityViewModel 和 CountryViewModel 派生自 EditorViewModel<T>
并分享已放入EditorViewModel<T>基类的基本Action
public RelayCommand NewCommand { get; private set; }
public RelayCommand SaveCommand { get; private set; }
等等……
我的问题是如何将命令从子视图模型公开到功能区?
由于第一个视图模型 CurrentSubView 没有实现这些命令,所以我收到“BindingExpression path error: 'NewCommand' property not found on 'object' ''MainViewModel'”..... p>
我设法通过我添加的 MainViewModel 中的一些代码绑定命令:
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; }
但仍然开放以获得更优雅的建议;)
【问题讨论】:
-
那么CityViewModel和CountryViewModel是在CurrentSubView中实例化的吗?能否设置 Fluent:Ribbon 的 DataContext 以使用正确的 ViewModel?
-
是的,但仅在按钮单击时,如
<Button Command="{Binding OpenView}" CommandParameter="Cities" Content="Cities" />和命令 OpenView 是 MainViewModel 上的 RelayCommand并且这有效 -
这看起来与您需要的相似。 stackoverflow.com/questions/1026342/…
-
是的,它与那个问题相似,但顺序相反 Child->Parent。我需要父子命令绑定
-
如果你有多个chile,父级应该如何知道应该执行哪个子级命令?
标签: c# wpf mvvm commandbinding