一、问题场景
对于ItemsControl
本身,默认不包含选中默认样式,内部子项默认是全填充,布局和效果如下:
<ScrollViewer VerticalScrollBarVisibility="Auto" BorderThickness="0"> <ItemsControl ItemTemplateSelector="{StaticResource ChatTemplateSelector}" x:Name="chats" Background="White" Margin="10"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel></StackPanel> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.Template> <ControlTemplate TargetType="{x:Type ItemsControl}"> <Grid> <ItemsPresenter></ItemsPresenter> </Grid> </ControlTemplate> </ItemsControl.Template> </ItemsControl> </ScrollViewer>
运行效果如下:
将ItemsControl
替换为ListBox
或ListView
出现内容无法全填充,
替换为ListBox
:
<ScrollViewer VerticalScrollBarVisibility="Auto" BorderThickness="0"> <ListBox ItemTemplateSelector="{StaticResource ChatTemplateSelector}" x:Name="chats" Background="White" Margin="10"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel></StackPanel> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.Template> <ControlTemplate TargetType="{x:Type ItemsControl}"> <Grid> <ItemsPresenter></ItemsPresenter> </Grid> </ControlTemplate> </ListBox.Template> </ListBox> </ScrollViewer>
替换为ListView
:
<ScrollViewer VerticalScrollBarVisibility="Auto" BorderThickness="0"> <ListView ItemTemplateSelector="{StaticResource ChatTemplateSelector}" x:Name="chats" Background="White" Margin="10"> <ListView.ItemsPanel> <ItemsPanelTemplate> <StackPanel></StackPanel> </ItemsPanelTemplate> </ListView.ItemsPanel> <ListView.Template> <ControlTemplate TargetType="{x:Type ItemsControl}"> <Grid> <ItemsPresenter></ItemsPresenter> </Grid> </ControlTemplate> </ListView.Template> </ListView> </ScrollViewer>
效果如下:
二、解决方案
实际本质原因为ListBox
或ListView
样式中,默认配置HorizontalContentAlignment
,默认为Left
,直接手动添加该内容水平全填充对齐Stretch
。
修改如下:
<ScrollViewer VerticalScrollBarVisibility="Auto" BorderThickness="0"> <ListBox HorizontalContentAlignment="Stretch" ItemTemplateSelector="{StaticResource ChatTemplateSelector}" x:Name="chats" Background="White" Margin="10"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel></StackPanel> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.Template> <ControlTemplate TargetType="{x:Type ItemsControl}"> <Grid> <ItemsPresenter></ItemsPresenter> </Grid> </ControlTemplate> </ListBox.Template> </ListBox> </ScrollViewer>
运行效果如下: