2010-06-05 141 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