我写了以下样式
<Style x:Key="StyleListViewItems" TargetType="ListView">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="DataTemplateListViewItems">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" Width="175" Height="175" Source="{controls:ConcatString AttachString=/JPMorganFxxR;component/Content/Icons/Items/, BindTo={Binding Path=Image}}"/>
<TextBlock Grid.Row="1" Height="24" Width="175" Text="{Binding Path=Name, Mode=OneWay}" IsEnabled="False" TextWrapping="WrapWithOverflow"
TextAlignment="Center" FontSize="16"/>
</Grid>
</DataTemplate>
我在列表视图中使用它们:
<ListView Name="LstItems" Width="Auto" Height="500" Margin="25" SelectionMode="Single" Background="Cornsilk"
ItemTemplate="{StaticResource DataTemplateListViewItems}"
ItemsSource="{Binding FxData.Item}"
Style="{StaticResource StyleListViewItems}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
</ListView>
这很好用,但是我得到一些错误,我不会解释:
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 'ListViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
为什么程序在我使用Wrappanel作为ItemsPanelTemplate时没有绑定到Alignments(没有这个没有错误)或者当它使用给定的itemsource时DataItem为null。在互联网上随处可见的例子中,它的完成方式完全相同。
提前致谢。
答案 0 :(得分:1)
可以通过设置默认内容对齐
来解决此问题<Style TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
<Setter Property="VerticalContentAlignment"
Value="Center" />
</Style>
原始tipp