赞
踩
转载:https://code.4noobz.net/wpf-change-color-of-a-row-in-a-datagrid-depending-on-the-value/
<Window x:Class="DataTrigger_Test.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" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid Margin="10" ItemsSource="{Binding Users}" AutoGenerateColumns="False" ColumnWidth="*" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" EnableRowVirtualization="false" EnableColumnVirtualization="false" CanUserAddRows="False" CanUserReorderColumns="False" CanUserResizeColumns="True"> <DataGrid.CellStyle> <Style TargetType="{x:Type DataGridCell}"> <Style.Triggers> <DataTrigger Binding="{Binding FirstName}" Value="Dolores"> <Setter Property="Foreground" Value="Green" /> </DataTrigger> <DataTrigger Binding="{Binding FirstName}" Value="Maeve"> <Setter Property="Foreground" Value="Blue" /> </DataTrigger> </Style.Triggers> </Style> </DataGrid.CellStyle> <DataGrid.Columns> <DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" MinWidth="150" /> <DataGridTextColumn Header="LastName" Binding="{Binding LastName}" MinWidth="150" /> </DataGrid.Columns> </DataGrid> </Grid> </Window>
using System.Windows;
namespace DataTrigger_Test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowVM();
}
}
}
注意使用了Prism
MVVM框架
using System.Collections.ObjectModel; using Microsoft.Practices.Prism.Mvvm; namespace DataTrigger_Test { public class MainWindowVM : BindableBase { private ObservableCollection<User> _users; public ObservableCollection<User> Users { get { return _users ?? (_users = new ObservableCollection<User>()); } set { if (value != _users) { _users = value; OnPropertyChanged(() => Users); } } } public MainWindowVM() { Users.Add(new User {FirstName = "Dolores", LastName = "Abernathy"}); Users.Add(new User {FirstName = "Maeve", LastName = "Millay"}); } } public class User { public string FirstName { get; set; } public string LastName { get; set; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。