wpf - 绑定命令到加载的视图模型
问题描述
我有一个部分MainMenuView
在ContentControl
. 的是。DataContext
_MainMenuView
MainMenuViewModel
我可以将主菜单中的按钮绑定到命令,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>
解决方案
你应该可以通过给你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 )提供的事件聚合器模式,或者您可以查看 Prism 的方法,它允许您创建其他命令可以附加到的命令。您可以为您的菜单创建复合命令,并从所选视图模型中动态附加或分离实际命令。CompositeCommand
推荐阅读
- r - 停止 R Shiny 动画已死
- ruby-on-rails - 每次当前迭代在多个示例中重用变量
- wordpress - 带有单选按钮的 Wordpress 自定义小部件
- php - 复选框、表单提交以及如何在循环中正确使用 array_fill?
- jsx - 在设置 onClick 的 jsx 中循环
- netbeans - 输入新示例的属性值以使用 Netbeans 将其标签预测为 RapidMiner Process
- java - .hasNext() 和 .next() 导致无限循环
- tensorflow - 在 keras 的 model.fit 中随机播放
- python - TensorFlow:SparseSoftmaxCrossEntropyWithLogits 错误?
- memory - CUDA - 固定内存与可分页内存的权衡