将命令绑定到加载的viewmodel

时间:2020-11-05 20:48:04

标签: wpf xaml mvvm

我的MainMenuView中有一个部分可以将选定的视图模型加载到ContentControl中。 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>

1 个答案:

答案 0 :(得分:0)

您应该可以通过为您的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.Micro Prism )提供的event aggregator pattern,或者您可以查看Prism的CompositeCommand方法,该方法可以使您创建其他命令可以附加的命令。您可以为菜单创建复合命令,并从所选视图模型动态附加或分离 real 命令。

相关问题