我試圖將我的 ListBoxItem 的內容垂直和水平居中,但我無法讓它作業。
我的樣式模板:
<Style x:Key="myListBoxItem" TargetType="ListBoxItem">
<Style.Resources>
<Style TargetType="Border">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect ShadowDepth="2" Direction="90" BlurRadius="4" Color="Black" Opacity="0.25"/>
</Setter.Value>
</Setter>
</Style>
</Style.Resources>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#fe3f3f"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontWeight" Value="DemiBold"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsSelected" Value="False"/>
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter Property="Background" Value="#e9e9e9"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"/>
</MultiTrigger.Setters>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Width" Value="160"/>
<Setter Property="Height" Value="75"/>
<Setter Property="Background" Value="White"/>
<Setter Property="FontSize" Value="19"/>
</Style>
以下是我應用這種樣式的方法:我的 XAML 中有一個簡單的 ListBox,并在代碼隱藏中將 ListBoxItems 附加到它。我以這種方式將每個 ListBoxItem 的 ResourceReference 設定為我的樣式:
foreach (var equipment in listEquipments)
{
var lbi = new ListBoxItem();
lbi.Content = equipment.Name;
lbi.SetResourceReference(StyleProperty, "myListBoxItem");
ListBox_Equipments.Items.Add(lbi);
}
我嘗試將 ListBoxItem 的HorizontalContentAlignmentand HorizontalContentAlignment(通過樣式模板)設定為Center,以及HorizontalAlignmentand VerticalAlignment,但沒有成功。我認為這可能與我的樣式模板有關。
我還嘗試了一些 ItemTemplates,例如:
<ListBox HorizontalContentAlignment="Center">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}" FontSize="72"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
到目前為止沒有運氣。
uj5u.com熱心網友回復:
AnItemTemplate不適用于 a ListBoxItem。
將 的 設定或系結ItemsSource到ListBox您的listEquipments:
ListBox_Equipments.ItemsSource = listEquipments;
...并將 the 設定ItemContainerStyle為ListBox您的自定義Style:
<ListBox x:Name="ListBox_Equipments"
ItemContainerStyle="{StaticResource myListBoxItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465772.html
