Tuesday, April 10, 2007

How to change listbox, combobox or listview selection and background color

This is, probably, one of most common questions about styling in WPF - how to change selected item background color in ListBox (ComboBox, ListView etc). The answer is really simple - look into default control templates of those controls. Those templates using system brushed in order to paint background colors. So, if you want to customize an appearance of those controls, you always can rewrite templates, but why to do it if the only thing you want is to change color brush of elements, so KISS [keep it stupid simple] rewrite those system brushed like this:

      <ComboBox Background="Red">

        <ComboBox.Resources>

          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />

          <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Green" />

          <SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Red" />

        </ComboBox.Resources>

        <TextBlock>TEST</TextBlock>

        <TextBlock>TEST</TextBlock>

        <TextBlock>TEST</TextBlock>

        <TextBlock>TEST</TextBlock>

        <TextBlock>TEST</TextBlock>

        <TextBlock>TEST</TextBlock>

        <TextBlock>TEST</TextBlock>

      </ComboBox>

That's all, folks. Now you have you own colored combo, that looks like this:

4 comments:

Cornel said...

Finally I get answer for this question. But, when the list box doesn't have the focus the color changes again. :(

Martin Rauscher said...

The code for the disabled control is:
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />

Maxim Alexeyev said...

I have a question not related to the subject, but I would really appreciate if you answer it.

I have a blog myself at www.blogger.com (http://discoveringdotnet.alexeyev.org) about .NET development. My question is:

How did you produce this nicely formatted XML or source code examples for your post?

Saiful Alam said...

Nice blog...
visit also asp.net example