.net ListBoxItem 产生“System.Windows.Data Error: 4”绑定错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3958173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:49:18  来源:igfitidea点击:

ListBoxItem produces "System.Windows.Data Error: 4" binding error

.netwpfxamllistboxlistboxitem

提问by BennoDual

I have created the fallowing ListBox:

我创造了休耕ListBox

<ListBox x:Name="RecentItemsListBox" Grid.Row="1" BorderThickness="0" Margin="2,0,0,0" SelectionChanged="RecentItemsListBox_SelectionChanged">
  <ListBox.Resources>
      <Style TargetType="{x:Type ListBoxItem}"
             BasedOn="{StaticResource {x:Type ListBoxItem}}">
          <Style.Triggers>
              <!--This trigger is needed, because RelativeSource binding can only succeeds if the current ListBoxItem is already connected to its visual parent-->
              <Trigger Property="IsVisible" Value="True">
                  <Setter Property="HorizontalContentAlignment"
                          Value="{Binding Path=HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
                  <Setter Property="VerticalContentAlignment"
                          Value="{Binding Path=VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
              </Trigger>
          </Style.Triggers>
      </Style>
  </ListBox.Resources>
  <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,2,0,0">
                <TextBlock Text="{Binding Number}" />
                <StackPanel Orientation="Vertical" Margin="7,0,0,0">
                    <TextBlock Text="{Binding File}" />
                    <TextBlock Text="{Binding Dir}" Foreground="DarkGray" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This will produce at runtime the fallowing Line in the OutputWindow of VisualStudio:

这将在运行时生成 VisualStudio 的输出窗口中的空闲行:

System.Windows.Data Error: 4 : 
 Cannot find source for binding with reference 'RelativeSource FindAncestor, 
 AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. 
 BindingExpression:Path=HorizontalContentAlignment; DataItem=null; 
 target element is 'ListBoxItem' (Name='');

Can someone give me a tip, how I can solve this?

有人可以给我一个提示,我该如何解决这个问题?

Update:

更新

I have added the Properties to the style to try to eliminate the warning/error.

我已将属性添加到样式中以尝试消除警告/错误。

回答by Etienne

The easiest way to solve this is to ensure that your Listboxhas a ItemContainerStyle. See the following example:

解决此问题的最简单方法是确保您的Listbox具有ItemContainerStyle。请参阅以下示例:

<ListBox x:Name="RecentItemsListBox" Grid.Row="1" BorderThickness="0" Margin="2,0,0,0" SelectionChanged="RecentItemsListBox_SelectionChanged">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
        </Style>
    </ListBox.ItemContainerStyle>

...

</ListBox>

What happens is that your Items are being created, and by default they look for parent's property which isn't defined. Explicitly defining it will solve this problem.

发生的情况是您的 Items 正在创建,默认情况下它们会查找未定义的父级属性。明确定义它将解决这个问题。

I had the same issue using a TreeView and changing the bound source for these templates would cause those warnings.

我在使用 TreeView 时遇到了同样的问题,更改这些模板的绑定源会导致这些警告。

回答by bsegraves

The answer over here resolved this issue for me:

这里的答案为我解决了这个问题:

ListBox with Grid as ItemsPanelTemplate produces weird binding errors

带有 Grid 作为 ItemsPanelTemplate 的 ListBox 会产生奇怪的绑定错误

Defining a top-level style (in my App.xaml) targeting the problem type "fixed" the issue for me. Here's a style that should work for you:

定义针对问题类型的顶级样式(在我的 App.xaml 中)为我“修复”了问题。这是一种应该适合您的样式:

<Style TargetType="{x:Type ListBoxItem}">
     <Setter Property="HorizontalContentAlignment" Value="Left" />
     <Setter Property="VerticalContentAlignment" Value="Top" />
</Style>

In my case, I was creating some TreeViewItems and then binding my TreeView to the created items. The binding error was occurring because the TreeViewItem's binding was being resolved before they were being added to the TreeView. The correct solution was to not create a TreeViewItem, but instead create a class that contained the data I needed (Header and Items). Just relaying my situation in case there are parallels with your own.

就我而言,我正在创建一些 TreeViewItems,然后将我的 TreeView 绑定到创建的项目。发生绑定错误是因为 TreeViewItem 的绑定在它们被添加到 TreeView 之前正在解析。正确的解决方案是不创建 TreeViewItem,而是创建一个包含我需要的数据(Header 和 Items)的类。只是传达我的情况,以防与您自己的情况有相似之处。

回答by akjoshi

Another workaround that worked for me was to suppress these errors (actually, it seems more appropriate to call them warnings) by setting the data binding source switch level as critical in constructor of the class or a top level window -

另一个对我有用的解决方法是通过在类的构造函数或顶级窗口中将数据绑定源开关级别设置为关键来抑制这些错误(实际上,将它们称为警告似乎更合适) -

#if DEBUG     
    System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level =
        System.Diagnostics.SourceLevels.Critical;
#endif

Ref.: How to suppress the System.Windows.Data Error warning message

参考:如何抑制 System.Windows.Data 错误警告消息

Update: This is not the best solution but for warnings which are harmful this looks good to me.

更新:这不是最好的解决方案,但对于有害的警告,这对我来说看起来不错。