首页 文章

Multiconverter上的WPF相对绑定路径到Ancestor

提问于
浏览
0

我有一个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 }}}" />

这非常有效 .

但我想要做的是在另一列中使用Multi-type转换器将TypeID从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路径错误:'object'''DatabaseItem'(HashCode = 35751240)'上找不到'DataContext'属性 . BindingExpression:Path = DataContext.Database.TypeList,RelativeSource = {RelativeSource AncestorType = {x:Type Window}; DataItem ='DatabaseItem'(HashCode = 35751240); target元素是'TextBlock'(Name =''); target属性是'Text'(类型'String')

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

为什么相同的Binding表达式工作并且不在同一个DataGrid中工作?

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

1 回答

  • 0

    这是因为你可能输错 Binding 的路径,实际上没有任何RelativeSource设置,它应该是这样的:

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

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

相关问题