.net - 绑定(bind)到数据网格中的命令

标签 .net wpf data-binding mvvm

我在 WPF 应用程序中使用 M-V-VM 模式。我将 ViewModel 绑定(bind)到 ContentControl 并使用窗口资源中定义的数据模板来呈现该 ViewModel 的 View (UserControl)。

在 ViewModel 中,我有一个项目集合。我将该集合绑定(bind)到 WPF 工具包中提供的数据网格。同样在 View 模型中,我定义了一个 RemoveItem 命令,该命令接受要删除的项目 ID 的参数。

我将如何绑定(bind)到数据网格中的该命令?网格的数据上下文就是那个集合,所以类似于:

<Button Command="{Binding Path=RemoveCommand}" CommandParameter="{Binding Path=id}">X</Button>

不起作用 - 它找不到命令。我想我需要进行 RelativeSource 绑定(bind),但那会是什么样子?祖先类型是 UserControl 还是 ContentControl?我的 ViewModel 作为 DataContext 驻留在哪里?

还是我离这儿很远?

最佳答案

是的,你只需要升一级。我会尝试绑定(bind) ElementName首先求助于RelativeSource仅在必要时。例如,我更喜欢这个:

<DataGrid x:Name="_grid">
    ...
        <Button Command="{Binding DataContext.RemoveItem, ElementName=_grid}"/>
    ...
</DataGrid>

也就是说,当涉及到元素名称和控件范围时,XAML 编译器可能会陷入困境,因此您可能需要求助于 RelativeSource :
<DataGrid x:Name="_grid">
    ...
  <Button Command="{Binding DataContext.RemoveItem, 
                    RelativeSource={RelativeSource FindAncestor, 
                                    AncestorType={x:Type DataGrid}}
                   }"/>
    ...
</DataGrid>

您只需要搜索直到数据上下文成为您的 View 模型。您可以搜索 UserControl如果你想 - 不确定它真的很重要。两者都是非常脆弱的绑定(bind),这就是为什么我更喜欢 ElementName方法。

关于.net - 绑定(bind)到数据网格中的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/581715/

相关文章:

c# - WPF 图像控件源绑定(bind)

c# - 直接将 DataGridView 绑定(bind)到 DataSet 失败

java - 如何将任何 Activity 或 fragment 的数据绑定(bind)对象传递给方法参数而不需要强制转换?

.net - 如何避免 File.Exists/File.Delete 或 Directory.Exists/Directory.Delete 中的竞争

c# - 带有 Intellisense 的开源 C# 语法编辑器

.net - ASP.NET MVC 2 中是否可以嵌套区域?

c# - 如何在 WebBrowser 控件中检测导航出

c# - 整行的 WPF TreeView 项目背景

c# - 从控件代码更新 XAML 控件属性值但保持绑定(bind)

wpf - ComboBox和 Entity Framework ,如何获取ID? (WPF-MVVM)