1
votes

I have a list box whose selection colour is default plain Solid Blue colour. I read this article "How To Change WPF ListBox SelectedItem Color?" here. I want to create style given in it to code behind. so that i can assign this style to my Listbox ItemContainerStyle property.

like

Style s = ......

MyListBox.ItemContainerStyle = s;

I want to make this in code behind because if user changes theme of my software then this style (Selection Colours) should recreate itself to match the changed theme colours.

<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>
1
What have you tried and what problems are you running into? Please edit the question to add this info, including any code samples you have (even if they are broken).Merlyn Morgan-Graham
@MerlynMorgan-Graham: I have edited my Question Please look into it now.Nikhil Agrawal
Here's a duplicate question: stackoverflow.com/questions/1729368/… - Start with that example, and let Intellisense help you with the rest.Merlyn Morgan-Graham
@MerlynMorgan-Graham I had look into itNikhil Agrawal

1 Answers

4
votes

I think you don't have a code behind version of this code, you just have to apply you're existing template to your listbox like below.

if your target is a template.

(NameOfListBox.SelectedItem as ListBoxItem).ContentTemplate = this.Resources["NameOfTemplate"] as DataTempate;
(NameOfListBox.SelectedItem as ListBoxItem).UpdateLayout();

if your target is a style.

 (NameOfListBox.SelectedItem as ListBoxItem).Style= this.Resources["NameOfStyle"] as DataTempate;
 (NameOfListBox.SelectedItem as ListBoxItem).UpdateLayout();

example

(lstMetaDataCards.SelectedItem as ListBoxItem).ContentTemplate = this.Resources["MetaDataCardAtEditState"] as DataTemplate;
(lstMetaDataCards.SelectedItem as ListBoxItem).UpdateLayout();