首页 > 解决方案 > 绑定命令到加载的视图模型

问题描述

我有一个部分MainMenuViewContentControl. 的是。DataContext_MainMenuViewMainMenuViewModel

我可以将主菜单中的按钮绑定到命令,SelectedViewModel还是必须引发事件?

<Fluent:Ribbon>
   <!--Userdata-->
   <Fluent:RibbonTabItem Header="Data" x:Name="TabVerm" Group="{Binding ElementName=VermittlerGroup}">
      <Fluent:RibbonGroupBox Header="Data">
         <Fluent:Button" Command="{Binding Path=DataContext.VermittlerSave, ElementName=VermittlerView}" Header="Save" LargeIcon="{iconPacks:FontAwesome Kind=SaveRegular,Width=30,Height=25}"></Fluent:Button>
         <Fluent:Button Header="Cancel" LargeIcon="{iconPacks:FontAwesome Kind=UndoAltSolid,Width=30,Height=25}"></Fluent:Button>
      </Fluent:RibbonGroupBox>
      <Fluent:RibbonGroupBox Header="Activate">
         <Fluent:Button Header="Aktivate User" LargeIcon="{iconPacks:FontAwesome Kind=StackExchangeBrands,Width=30,Height=25}"></Fluent:Button>
         <Fluent:Button  Header="New User" LargeIcon="{iconPacks:FontAwesome Kind=PlusCircleSolid,Width=30,Height=25}"></Fluent:Button>
      </Fluent:RibbonGroupBox>
   </Fluent:RibbonTabItem>
</Fluent:Ribbon>
<Grid Grid.Row="1">
   <ContentControl Grid.Row="1" Content="{Binding SelectedViewModel}"/>
</Grid>

标签: wpfxamlmvvm

解决方案


你应该可以通过给你ContentControl的名字来做到这一点。

<ContentControl Grid.Row="1" x:Name="MyContentControl" Content="{Binding SelectedViewModel}"/>

然后您可以在命令绑定中引用它及其Content保存视图模型的属性,例如:

<Fluent:Button" Command="{Binding Content.VermittlerSave, ElementName=MyContentControl}" Header="Save" LargeIcon="{iconPacks:FontAwesome Kind=SaveRegular,Width=30,Height=25}"/>

当然,这仅适用于任何选定的视图模型包含绑定命令的情况。

绑定的替代方案是与事件通信,例如使用大多数 MVVM 框架(如Caliburn.MicroPrism )提供的事件聚合器模式,或者您可以查看 Prism 的方法,它允许您创建其他命令可以附加到的命令。您可以为您的菜单创建复合命令,并从所选视图模型中动态附加或分离实际命令。CompositeCommand


推荐阅读