Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the background color of a listview item in WPF using databinding?

I have a listview that binds to an observable collection of type person. I added the following property to my person object:

public System.Windows.Media.SolidColorBrush Brush { get; set; }

How do I set the color of my item in the listview by binding to this property? Below is my XAML.

<Window x:Class="ObservableTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ObservableTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5,5,5">

            <TextBlock x:Name="lblName" Text="Name"></TextBlock>
            <TextBox x:Name="txtName"></TextBox>

            <TextBlock x:Name="lblAddress" Text="Address"></TextBlock>
            <TextBox x:Name="txtAddress"></TextBox>

            <Button Grid.Column="0" Width="100" Height="20" Margin="5,5,5,5" x:Name="btnNames" Click="btnNames_Click" Content="Add"></Button>           
        </StackPanel>

        <ListView x:Name="lstNames" Margin="5,5,5,5" Grid.Column="1" Grid.Row="0">
            <ListView.View>
                <GridView x:Name="grdName">
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
                    <GridViewColumn Header="Address" DisplayMemberBinding="{Binding Address}"/>

                </GridView>
            </ListView.View>
        </ListView>               
    </Grid>
</Window>
like image 255
Bill Greer Avatar asked Sep 14 '25 08:09

Bill Greer


1 Answers

Try the Style property.

One can add this code to the ListView and then it should set the background of the ListViewItems to the Brush color.

<ListView>
   <ListView.ItemContainerStyle>
      <Style TargetType="{x:Type ListViewItem}">
           <Setter Property="Background" Value="{Binding Brush}" />
      </Style>
   </ListView.ItemContainerStyle>

   ...

</ListView>
like image 173
Florin M Avatar answered Sep 16 '25 23:09

Florin M