Dot-Net

ListBoxItem 產生“System.Windows.Data Error: 4”綁定錯誤

  • October 18, 2010

我創造了休耕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>

這將在執行時在 VisualStudio 的 OutputWindow 中生成閒置線:

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='');

有人可以給我一個提示,我該如何解決這個問題?

更新

我已將屬性添加到樣式中以嘗試消除警告/錯誤。

解決此問題的最簡單方法是確保您的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>

發生的情況是您的項目正在被創建,並且預設情況下它們會查找未定義的父級屬性。明確定義它將解決這個問題。

我在使用 TreeView 時遇到了同樣的問題,更改這些模板的綁定源會導致這些警告。

引用自:https://stackoverflow.com/questions/3958173