WPF:如何调试绑定错误?

Jon*_*len 13 wpf binding

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

System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1''.BindingExpression:路径= VerticalContentAlignment; 的DataItem = NULL; target元素是'ListBoxItem'(Name =''); target属性是'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>
Run Code Online (Sandbox Code Playgroud)

Ray*_*rns 10

我还打算推荐Bea Stollnitz的文章,但Jonathan Allen在我还在输入这篇文章的时候得到了他的职位.我还推荐此博客条目中的链接.

在这种特殊情况下,您可以看到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}}" />
Run Code Online (Sandbox Code Playgroud)

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

有些事要寻找:

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

希望这会引导您朝着正确的方向前进.