在列表框项 wpf 周围显示边框时的图像移动
本文关键字:边框 图像 移动 显示 周围 列表 wpf | 更新日期: 2023-09-27 18:30:43
我正在使用列表框来显示图像。选择列表框项后,它会在图像周围显示边框。它不是在图像周围显示边框,而是将图像向右移动。
列表框样式:
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=UriSource}"
Stretch="Fill"
Width="639" Height="530">
</Image>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility"
Value="Disabled"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility"
Value="Disabled"/>
<Setter Property="HorizontalContentAlignment"
Value="Left"/>
<Setter Property="VerticalContentAlignment"
Value="Center" />
</Style>
列表框项样式:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="Padding" Value="0,0,0,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd"
SnapsToDevicePixels="True"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="0"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource BorderColor}"/>
<Setter Property="BorderThickness" TargetName="Bd" Value="12" />
<Setter Property="Width" Value="639" />
<Setter Property="Height" Value="530" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource BorderColor}"/>
<Setter Property="BorderThickness" TargetName="Bd" Value="12" />
<Setter Property="Width" Value="639" />
<Setter Property="Height" Value="530" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这是因为在ListBoxItem
样式中,您将边框的粗细从正常情况下的0
更改为选择项目时的12
。这会将内容移动 12pt。
您这里有几种可能的解决方案,有两种可能性:
- 始终使用 12pt 边框,但在未选中状态下使用
Transparent
或{x:Null}
画笔 - 在
ContentPresenter
上使用12
边距,并将其设置为在触发器中0
使用布局转换,而不是使用渲染转换。 设置边距="-2,0,-2,0" 填充="-1,0,-1,0" 表示列表框。和