【问题标题】:WPF how to expose binding source as a resourceWPF如何将绑定源公开为资源
【发布时间】:2020-10-21 08:02:27
【问题描述】:

我有一个位于 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(如果可能的话)。

【问题讨论】:

  • 为什么要将Source 设置为对象?您应该做的是将命令属性添加到子视图的DataContext 并直接绑定到这个。或者坚持你目前的方法。
  • 我的孩子视图没有特定的DataContext。子代从父代继承DataContext。在我的情况下 Child 本身不是一个视图,child 也可以在 Parent 中声明。我只是想移动很多 xaml 来分隔 UserControl,这样 Parent 就更干净了。

标签: wpf xaml binding resources


【解决方案1】:

你可以在 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}">

如果虚拟机不需要是动态的,那么你可以使用静态资源:

<Button Command="{Binding MyCommand, Source={StaticResource VM}}"
        CommandParameter="{Binding}">

如果由于某种原因不方便,您可以将资源设置为实现 inotifypropertychanged 的​​视图模型,并将您感兴趣的特定视图模型作为其属性:

    <Button Command="{Binding ParentViewmodel.MyCommand, Source={StaticResource VM}}"
        CommandParameter="{Binding}">

这将允许您在命令上切换 ParentViewmodel。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-01
    • 2013-02-02
    • 2023-04-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2012-03-02
    • 2011-09-12
    相关资源
    最近更新 更多