【问题标题】:WPF relative binding path on Multiconverter to AncestorMulticonverter 到 Ancestor 上的 WPF 相对绑定路径
【发布时间】:2014-10-15 09:35:06
【问题描述】:

我有一个 DataGrid,其中一列是 int TypeID,但我将它呈现为 ComboBox,并使用包含 [TypeID, Name] 映射的绑定值列表 (TypeList) 将 TypeID 值映射到字符串。此绑定列表在 XAML 中表示为

<ComboBox SelectedValue="{Binding TypeID}" 
          DisplayMemberPath="Name"
          SelectedValuePath="TypeID"
          ItemsSource="{Binding Path=DataContext.Database.TypeList, RelativeSource={RelativeSource AncestorType={x:Type Window }}}" />

这很好用。

但我想做的是在另一列中使用多类型转换器将从 TypeID 映射的名称呈现为简单字符串。在我的 XAML 和 same 数据网格中,我有

<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Width="20">
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource TypeIDConverter}">
            <Binding Path="TypeID" />
            <Binding Path="DataContext.Database.TypeList, RelativeSource={RelativeSource AncestorType={x:Type Window }}" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

这根本不起作用。

在类型转换器中,我得到DependencyProperty.UnsetValue 作为第二个参数。从IMultiValueConverter always passes in DependencyProperty.UnsetValue for list我知道WPF系统找不到我的绑定。

这也出现在我收到此错误的应用程序的输出窗口中:

System.Windows.Data 警告:40:BindingExpression 路径错误: 在“对象”“DatabaseItem”上找不到“DataContext”属性 (哈希码=35751240)'。 BindingExpression:Path=DataContext.Database.TypeList, RelativeSource={RelativeSource AncestorType={x:类型窗口}; DataItem='DatabaseItem' (HashCode=35751240);目标元素是 '文本块'(名称='');目标属性是“文本”(类型“字符串”)

这就是我感到困惑的地方。我以为我的 RelativeSource 正在查找窗口根目录,然后在那里寻找 DataContext。相反,这个错误告诉我它正在 DataGrid 的行项 (DatabaseItem) 上寻找 DataContext。

为什么同一个 Binding 表达式在同一个 DataGrid 中有效而无效?

我需要做什么来解决这个问题?

【问题讨论】:

    标签: wpf xaml data-binding datagrid


    【解决方案1】:

    因为你可能打错了Binding的Path,实际上并没有设置RelativeSource,应该是这样的:

    <Binding Path="DataContext.Database.TypeList" 
             RelativeSource="{RelativeSource AncestorType={x:Type Window }}"/>
    

    和以前一样,您实际上将整个Path 设置为"DataContext.Database.TypeList, RelativeSource={RelativeSource AncestorType={x:Type Window }}"

    【讨论】:

    • 换句话说,PEBKAC。谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多