【发布时间】:2011-04-26 20:51:30
【问题描述】:
我已经创建了休闲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='');
谁能给我一个提示,我该如何解决这个问题?
更新:
我已将属性添加到样式中以尝试消除警告/错误。
【问题讨论】:
-
你需要那种风格吗?为什么不能在数据模板中的 stackpanel/textblock 上设置对齐方式?
标签: .net wpf xaml listbox listboxitem