如何解决WPF如何将绑定源公开为资源
我在ParentView中有一个TabControl。在该TabControl中,我有一个ChildView,其中包含一个按钮,该按钮的命令绑定到ParentViewModel的ICommand:
<Button Command="{Binding DataContext.MyCommand,RelativeSource={RelativeSource AncestorType={x:Type local:ParentView}}}"
CommandParameter="{Binding}">
实际上其中一些。有没有一种方法可以从那个RelativeSource和DataContext创建UserControl资源,这样我就可以像这样声明我的按钮了:
<Button Command="{Binding MyCommand,Source={StaticResource MyParentsDataContext}}"
CommandParameter="{Binding}">
修改
到目前为止,我的想法是:
<UserControl.Resources>
<RelativeSource x:Key="Parent" AncestorType="{x:Type local:ParentView}" />
</UserControl.Resources>
<Button Command="{Binding DataContext.MyCommand,RelativeSource={StaticResource Parent}}"
CommandParameter="{Binding}">
稍干些,可读性更好,但仍然不确定如何摆脱DataContext
。
解决方法
您可以将任何喜欢的东西放在application.current.resources中。
这就像是一种带有字符串键和对象值的内存字典。
因此,您可以在合并到app.xaml中的资源字典中添加类的实例:
<local:AnyViewModel x:Key="VM"/>
如果您不需要任何参数,那么您可能会发现根本不需要更改它。
如果该父视图模型有更多功能,则可以替换虚拟版本。
如果您随后在另一个资源字典中的实例中使用同一键在更广泛的范围内合并或在代码中对其进行设置:
Application.Current.Resources["VM"] = newInstance;
然后它将替换绑定将在资源中找到的内容。
如果您想动态地进行操作,那么请记住动态资源的一些技巧。
您需要:
<Button DataContext="{DynamicResource VM}" Command="{Binding MyCommand}"
CommandParameter="{This is now a complication}">
如果虚拟机不需要是动态的,那么可以使用staticresource:
<Button Command="{Binding MyCommand,Source={StaticResource VM}}"
CommandParameter="{Binding}">
如果由于某种原因这不方便,则可以将资源设置为实现了inotifypropertychanged的viewmodel,并且将特定的viewmodel作为该属性的属性:
<Button Command="{Binding ParentViewmodel.MyCommand,Source={StaticResource VM}}"
CommandParameter="{Binding}">
这将允许您在命令上切换出ParentViewmodel。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。