2010-06-05 140 views
12

我在我的输出窗口得到这个:WPF:我如何调试绑定错误?

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type '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> 

回答

8

我也打算建议Bea Stollnitz's article但乔纳森 - 阿伦得到了他在后而我仍然在打字。我也推荐链接this blog entry

在这种特殊情况下,您可以看到ListBoxItem的某个位置有一个FindAncestor绑定到失败的ItemsControl。这告诉你马上有一个ListBoxItem的地方,可以是:

  1. 不是在可视化树,或
  2. 没有下一个ItemsControl(列表框是一个ItemsControl)

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

望着系统主题(随Expression Blend和也可通过NET的反射的BAMLViewer加载项),我们可以看到这一点:

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

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

有些事情要寻找:

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

希望这会使您朝正确的方向发展。

+0

给你的任务,不,没有和没有。唯一有趣的是ItemsSource是一个数据表。 – 2010-06-05 20:46:04

+0

但是,嘿,至少你给了我足够的信息,知道它在样式表中。 – 2010-06-05 20:52:23

3

我遇到了与TreeView类似的问题(虽然我的数据绑定错误显示为信息)。

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

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

我遇到了同样的问题,并使用您的方法解决了这个问题。谢谢! – cordialgerm 2012-03-08 20:12:02