如何使用数据绑定在WPF中设置列表视图项的背景颜色? [英] How do I set the background color of a listview item in WPF using databinding?

查看:116
本文介绍了如何使用数据绑定在WPF中设置列表视图项的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到可观察的person类型集合的列表视图。我在个人对象中添加了以下属性:

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; }

如何通过绑定到此属性来设置列表视图中项目的颜色?以下是我的XAML。

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>


推荐答案

尝试样式属性。

可以将此代码添加到 ListView 中,然后应设置 ListViewItems 到 Brush 颜色。

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>

这篇关于如何使用数据绑定在WPF中设置列表视图项的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆