C# WPF Listview 如何设置某一行的颜色
推荐于2017-12-16 · 知道合伙人软件行家
你得自己写个转换器,在绑定模板中将某个属性转换从而返回背景色,即可
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<local:BGConvert x:Key="bgconvert" ></local:BGConvert>
</Grid.Resources>
<ListView Name="listView" >
<ListView.View>
宴键 <GridView >
<GridViewColumn DisplayMemberBinding="{Binding Name}"
Header="Name" Width="120"/>
<GridViewColumn
Header="Age" Width="120">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Background="{Binding Path=Age,Converter={StaticResource bgconvert} }">
<TextBlock Text="{Binding Age}"></TextBlock>
</StackPanel>
尺团 </DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
List<Person> ps = new List<Person>();
ps.Add(new Person() { Name = "Tom", Age = 80 });
ps.Add(new Person() { Name = "jack", Age = 91 });
listView.ItemsSource = ps;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class BGConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
晌困巧 if((int)value>90)
{
return new SolidColorBrush(Colors.Red);
}
else
return new SolidColorBrush(Colors.White);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}