【问题标题】:WPF: How do I debug binding errors?WPF:如何调试绑定错误?
【发布时间】:2011-02-28 05:19:54
【问题描述】:

我在输出窗口中得到了这个:

System.Windows.Data 错误:4:找不到与引用'RelativeSource FindAncestor,AncestorType='System.Windows.Controls.ItemsControl',AncestorLevel='1''的绑定源。绑定表达式:路径=垂直内容对齐;数据项=空;目标元素是'ListBoxItem'(名称='');目标属性是“VerticalContentAlignment”(类型“VerticalAlignment”)

这是我的 XAML,运行时看起来正确

        <GroupBox Header="Grant/Deny Report">
            <ListBox ItemsSource="{Binding  Converter={StaticResource MethodBinder}, ConverterParameter=GrantDeny, Mode=OneWay}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Label Content="{Binding Entity}"/>
                            <Label Content="{Binding HasPermission}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </GroupBox>

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    我还打算推荐Bea Stollnitz's article,但乔纳森艾伦在我还在打字的时候就收到了他的帖子。我也推荐this blog entry中的链接。

    在这种特殊情况下,您可以看到某个 ListBoxItem 有一个 FindAncestor 绑定到一个失败的 ItemsControl。这会立即告诉您在某处有一个 ListBoxItem:

    1. 不在可视化树中,或
    2. 不在 ItemsControl 下(ListBox 是 ItemsControl)

    此外,您知道有人在某处将 ListBoxItem 的 VerticalContentAlignment 属性绑定到 FindAncestor。

    查看系统主题(随 Expression Blend 提供,也可通过 NET Reflector 的 BAMLViewer 插件获得),我们看到:

    <Style x:Key="{x:Type ListBoxItem}">
      <Setter Property="VerticalContentAlignment"
              Value="{Binding Path=VerticalContentAlignment,RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}" />
    

    这解释了绑定的来源。下一个问题是,如何创建不在 ListBox(或其他 ItemsControl)下的 ListBoxItem?

    一些需要寻找的东西:

    • 您是否在任何地方的代码中构造 ListBoxItems?
    • 您的 XAML 中是否明确指定了任何 ListBoxItem?
    • 您是否有任何代码可以手动操作 ListBox 中的项目?

    希望这会引导你朝着正确的方向前进。

    【讨论】:

    • 对于您的问题,不,不,不。唯一有趣的是 ItemsSource 是一个数据表。
    • 但是,至少你给了我足够的信息,让我知道它在样式表中。
    【解决方案2】:

    我在 TreeView 中遇到了类似的问题(尽管我的数据绑定错误显示为信息性错误)。

    我通过在 TreeView 资源中为 TreeViewItem 定义隐式样式解决了这个问题。在该样式中,我定义了缺少的垂直和水平内容对齐属性。

    <TreeView.Resources>
         <Style TargetType="{x:Type TreeViewItem}" >
              <Setter Property="VerticalContentAlignment" Value="Stretch"/>
              <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
         </Style>
    </TreeView.Resources>
    

    【讨论】:

    • 我遇到了同样的问题并使用您的方法解决了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多