1

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>
H.B.
  • 166,899
  • 29
  • 327
  • 400
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208

1 Answers1

4

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();
Allan Chua
  • 9,305
  • 9
  • 41
  • 61