我有一个列表框,其选择颜色是默认的纯蓝色。我阅读了这篇文章“How To Change WPF ListBox SelectedItem Color?” here .我想创建其中给定的样式以进行编码。这样我就可以将此样式分配给我的 Listbox ItemContainerStyle 属性。
喜欢
样式 s = ......
MyListBox.ItemContainerStyle = s;
我想在代码隐藏中实现这一点,因为如果用户更改我的软件的主题,那么该样式(选择颜色)应该重新创建自身以匹配更改后的主题颜色。
<Style x:Key="SimpleListBoxItem" TargetType="ListBoxItem">
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Border" Padding="2" SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background" Value="{StaticResource AuthorGradient}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
请您参考如下方法:
我认为您没有此代码的代码隐藏版本,您只需将现有模板应用到您的列表框,如下所示。
如果您的目标是模板。
(NameOfListBox.SelectedItem as ListBoxItem).ContentTemplate = this.Resources["NameOfTemplate"] as DataTempate;
(NameOfListBox.SelectedItem as ListBoxItem).UpdateLayout();
如果您的目标是一种样式。
(NameOfListBox.SelectedItem as ListBoxItem).Style= this.Resources["NameOfStyle"] as DataTempate;
(NameOfListBox.SelectedItem as ListBoxItem).UpdateLayout();
例子
(lstMetaDataCards.SelectedItem as ListBoxItem).ContentTemplate = this.Resources["MetaDataCardAtEditState"] as DataTemplate;
(lstMetaDataCards.SelectedItem as ListBoxItem).UpdateLayout();
