将XAML样式转换为样式背后的代码?
问题描述:
我有一个列表框,其选择颜色是默认纯色纯蓝色。我读过这篇文章“如何更改WPF ListBox SelectedItem颜色?” here。我想要创建其中的代码以在后面编写代码。以便我可以将此样式分配给我的Listbox ItemContainerStyle属性。将XAML样式转换为样式背后的代码?
像
样式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();
你尝试过什么,并且你遇到了什么问题?请编辑问题以添加此信息,包括您拥有的任何代码示例(即使它们已损坏)。 –
@ MerlynMorgan-Graham:我编辑了我的问题请现在查看它。 –
这里有一个重复的问题:http://stackoverflow.com/questions/1729368/creating-a-style-in-code-behind-从那个例子开始,让Intellisense帮助你。 –