Search code examples
wpfliststylespixelsense

WPF: Style ListBoxItem to unify colors


I am starting with WPF development on a touch device. Although .NET and WPF seem to be an amazing technology, I am somewhat lost.

I am developing a generic control. I defined an UserControl which contains a Grid, some buttons and a SurfaceListBox. In the actual C#-code I am handling events and add new elements to the list box by manipulation the listItems-Attribute. This works fine so far.

Now I would like to change the style of the list items - I would like to make their background transparent if they are not selected, and completely white if they are. Unfortunately the following piece of code simply does not work. It just sets the background color of the list item text to white, but not the whole item.

Update: Now it works!

<UserControl x:Class="SGEditor.MyControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         xmlns:my="http://schemas.microsoft.com/surface/2008" UseLayoutRounding="True">
<UserControl.Resources>
    <Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
        <Setter Property="Background" Value="Transparent" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="White" />
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

<Grid>        
    <my:SurfaceListBox Width="300" Height="300" />
</Grid>
</UserControl>

Thank you!

Hans


Solution

  • I don't know exactly how to do what you want to do, but I'm pretty sure you can't reassign a static system value like you're trying to do in x:Key. That's just a name you use to reference the resource later in the xaml, like MyBackgroundColor or whatever.

    I think what you need to do is something with triggers in the style for your control that set the appropriate properties for the elements you want to change. Hopefully someone else will shed more light on that, since I rarely do that fancy stuff. =)