简单的改变需求
通过setter
设置颜色值,可直接改变,不需要条件判断的简单需求
<DataGridItemsSource="{Binding TableColorModels}"><DataGrid.RowStyle><StyleTargetType="DataGridRow"><SetterProperty="Background"Value="LightPink"/><Style.Triggers><TriggerProperty="IsMouseOver"Value="True"><SetterProperty="Background"Value="LightGray"/></Trigger><TriggerProperty="IsSelected"Value="True"><SetterProperty="Background"Value="#90F670"/><SetterProperty="Foreground"Value="White"/></Trigger></Style.Triggers></Style></DataGrid.RowStyle><DataGrid.Columns><DataGridTextColumnHeader="第一项"Binding="{Binding item1}"></DataGridTextColumn><DataGridTextColumnHeader="第二项"Binding="{Binding item2}"></DataGridTextColumn><DataGridTextColumnHeader="第三项"Binding="{Binding item3}"></DataGridTextColumn></DataGrid.Columns></DataGrid>
需要通过表格值进行改变时
我们可以通过转换器IValueConverter
或者IMultiValueConverter
获取到数据,然后根据你想要的条件进行颜色值的返回。
//TableColorView.xaml<Windowx:Class="Demo.TableColorView"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:Demo"xmlns:common="clr-namespace:Demo.Common"mc:Ignorable="d"Title="MainWindow"Height="450"Width="800"><Window.Resources><common:MultiBindingConverterx:Key="MultiBindingConverter"/></Window.Resources><Grid><DataGridItemsSource="{Binding TableColorModels}"><DataGrid.RowStyle><StyleTargetType="DataGridRow"><SetterProperty="Background"><Setter.Value><MultiBindingConverter="{StaticResource MultiBindingConverter}"><BindingPath="."/></MultiBinding></Setter.Value></Setter></Style></DataGrid.RowStyle><DataGrid.Columns><DataGridTextColumnHeader="第一项"Binding="{Binding item1}"></DataGridTextColumn><DataGridTextColumnHeader="第二项"Binding="{Binding item2}"></DataGridTextColumn><DataGridTextColumnHeader="第三项"Binding="{Binding item3}"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid></Window>
//MultiBindingConverter.csusingSystem; usingSystem.Windows.Data; usingSystem.Windows.Media; namespaceDemo.Common{ /// <summary>/// 绑定多参数的值转换器/// </summary>publicclassMultiBindingConverter : IMultiValueConverter { publicobjectConvert(object[] values, TypetargetType, objectparameter, System.Globalization.CultureInfoculture) { if (values!=null) { returnBrushes.LightBlue; } else { return""; } } publicobject[] ConvertBack(objectvalue, Type[] targetTypes, objectparameter, System.Globalization.CultureInfoculture) { thrownewNotImplementedException(); } } }
效果预览