WPF: How do I debug binding errors?

前端 未结 2 1619
别跟我提以往
别跟我提以往 2021-02-05 19:20

I\'m getting this in my output Window:

System.Windows.Data Error: 4 : Cannot find source for binding with reference \'RelativeSource FindAncestor, Ancesto

相关标签:
2条回答
  • 2021-02-05 19:51

    I was also going to recommend Bea Stollnitz's article but Jonathan Allen got his post in while I was still typing this one. I also recommend the links in this blog entry.

    In this particular case you can see that somewhere a ListBoxItem has a FindAncestor binding to an ItemsControl that is failing. That tells you right away there is a ListBoxItem somewhere that is either:

    1. Not in the visual tree, or
    2. Not under an ItemsControl (a ListBox is an ItemsControl)

    In addition, you know that someone, somewhere, is binding a ListBoxItem's VerticalContentAlignment property to FindAncestor.

    Looking at the system themes (shipped with Expression Blend and also available through NET Reflector's BAMLViewer Add-in), we see this:

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

    This explains where the binding comes from. The next question is, how is a ListBoxItem being created that is not under a ListBox (or other ItemsControl)?

    Some things to look for:

    • Are you constructing ListBoxItems in code anywhere?
    • Is there any ListBoxItem explicitly specified in your XAML?
    • Do you have any code that manually manipulates the items in ListBox?

    Hopefully this will head you in the right direction.

    0 讨论(0)
  • 2021-02-05 19:51

    I ran into a similar problem with the TreeView (though my data binding errors showed up as being Informational).

    I solved the problem by defining an implicit style in the TreeView resource for TreeViewItem. Within that style I defined the missing vertical and horizontal content alignment properties.

    <TreeView.Resources>
         <Style TargetType="{x:Type TreeViewItem}" >
              <Setter Property="VerticalContentAlignment" Value="Stretch"/>
              <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
         </Style>
    </TreeView.Resources>
    
    0 讨论(0)
提交回复
热议问题