【问题标题】:WPF - binding in data template to ViewModel, instead of individual recordWPF - 将数据模板绑定到 ViewModel,而不是单个记录
【发布时间】:2023-03-23 15:00:01
【问题描述】:

我有一个包含 Telerik RadGridView 的 WPF 用户控件。控件的数据上下文被设置为 MyViewModel 类的一个实例。 MyViewModel 类有一个 myRecords 属性,类型为 ObservableCollection。 RadGridView 是这样绑定的:

ItemsSource="{Binding myRecords}"

在 RadGridView 中,我定义了许多列,其中包含绑定到 MyRecords 属性的 DataTemplates。这工作正常。

我添加了一个包含删除按钮的列。或者更确切地说,它包含一个 DataTemplate,其中包含一个标记为“删除”的按钮。这与记录中定义的命令绑定:

<telerik:GridViewColumn.CellTemplate>
    <DataTemplate>
        <Button 
                Command="{Binding deleteCommand}"
                CommandParameter="{Binding}">
            <Label>Delete</Label>
        </Button>
    </DataTemplate>
</telerik:GridViewColumn.CellTemplate>

这很好用。我在 MyRecord 上定义的 ICommand 属性执行。

但事情是这样的——这不是我想要这段代码的地方。我不想在 MyRecord 上运行一个方法,我想在 MyViewModel 上运行一个方法,将适当的 MyRecord 作为参数传递。上面的 CommandParameter="{Binding}" 元素传递了适当的 MyRecord,因此该部分很好。但我无法弄清楚如何将按钮的命令绑定到 MyViewModel 对象上的 ICommand,而不是 MyRecord。

我一直在使用RelativeSource 和AncestorType,但一无所获。

我们将不胜感激。

【问题讨论】:

    标签: wpf xaml binding telerik datatemplate


    【解决方案1】:

    一种可能的方法是为您的记录使用 ViewModel,它会包装您的模型记录并包含 ICommand 引用。当为每条记录初始化一个recordViewModel时

    recordViewModel.deleteCommand = myViewModel.deleteCommand;
    

    其中 recordViewModel 和 myViewModel 是相应类的实例。

    这样当点击行中的Delete按钮时,父DataContext中的deleteCommand就会执行。

    更新:我找到了一个潜在的替代解决方案,您可以在其中绑定到不同的元素,这样您就不会局限于项目的数据上下文,而是使用您指定的任何元素的数据上下文。

    Command="{Binding DataContext.MyCommand, ElementName=LayoutRoot}"
    

    参考:http://blog.kevindockx.com/post/MVVM-challenge-binding-to-a-command-from-inside-an-ItemsControl-DataTemplate.aspx

    【讨论】:

    • 我想我可以做到。目前,我的 MyRecord 类是在一个不依赖于 PresentationCore.dll 的程序集中定义的,我想保持这种方式。另一种方法是通过 ObservableCollection 填充包含 MyRecords 的包装类的实例,或者,也许我可以在我的 ViewModel 程序集中定义一个 ExtensionMethod...
    【解决方案2】:

    您可以使用 FindAncestor 进行此操作,如下所示:{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}

    我认为这将是一个更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多