c# - 相同的绑定(bind)适用于 1 个 XAML 项目,但对另一个无效

标签 c# xaml data-binding datacontext converters

productColumn2 的绑定(bind)在两种情况下都完美无缺。当我为每个添加一个转换器时,productColumn1 调用了转换器;但在从可观察集合加载时始终将其值设置为 null,或在分配时将其值设置为产品(但实际上并未分配可观察集合)。

问题与 DataContext 和 LogicalTree 有关。 ProductSelectorTextBoxUserControl 的 DataContext 本身就是它自己,并用于它自己的代码。我希望能够将其“文本”属性绑定(bind)到我的可观察集合,如在 productColumn2 中。到目前为止,我似乎无法将 ProductSelectorTextBoxUserControl DataContext 设置为此处使用的 DataContext。

<DataGrid ItemsSource="{Binding Path=ObservableCollectionItems, Mode=OneWay}" AutoGenerateColumns="False" EnableRowVirtualization="True" >
<DataGrid.Columns>
    <DataGridTemplateColumn x:Name="productColumn1" SortMemberPath="Product" >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <productSelector:ProductSelectorTextBoxUserControl Text="{Binding Path=Product, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=LostFocus, ValidatesOnExceptions=True}" /> 
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn x:Name="productColumn2" Binding="{Binding Path=Product, Mode=TwoWay, NotifyOnSourceUpdated=True}" />            
</DataGrid.Columns>

最佳答案

如果 ProductSelectorTextBoxUserControlDataContext 设置为自身,则 Binding 将无法找到 Product 属性(property),因为它不存在。您需要修改您的绑定(bind),以便它知道在哪里可以找到 Product 属性;这样的事情可能会起作用:

<productSelector:ProductSelectorTextBoxUserControl Text="{Binding Path=Product, RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=LostFocus, ValidatesOnExceptions=True}" />

通过添加 RelativeSource,您告诉绑定(bind)在 DataGridRow.DataContext 中查找 Product 属性。

更新

您是否尝试过 {RelativeSource AncestorType={x:Type DataGridRow}}?您应该以行而不是网格为目标。

ItemContainerGenerator 创建每个 DataGridRow 时,它将行的 DataContext 设置为 ObservableCollectionItems 中的相应项目。所以,逻辑树是这样的:

  • DataGrid(DataContext = 定义 ObservableCollectionItems 的对象)
    • DataGridRow (DataContext = ObservableCollectionItems[0])
      • ProductSelectorTextBoxUserControl (DataContext = self)
    • DataGridRow (DataContext = ObservableCollectionItems[0])
      • ProductSelectorTextBoxUserControl (DataContext = self)

网格的 DataContext 不公开 Product 属性,它是在集合中的每个元素上定义的(除非我遗漏了什么)。 Product 属性应该在每一行的上下文中。

关于c# - 相同的绑定(bind)适用于 1 个 XAML 项目,但对另一个无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11849306/

相关文章:

c# - 将图像旋转 n 度

c# - 如何以编程方式关闭消息对话框

c# - 更新到 .net core 2.2 后信号 r 不工作

c# - WPF 中的源绑定(bind),如 Asp.Net

c# - Autocompletebox 不清除键盘笔画

c# - 以匿名类作为数据源的 BindingSource 列

c# - asp.net 回发超时

c# - Template10:AppBarButton:带有 TextBox 的内容不允许用户输入空格

c# - 如何在 XAML 模板中使用 WPF 自定义控件属性?

asp.net - 如何以声明方式创建带有数据绑定(bind)参数的 RouteUrls?