DataGrid изменить цвет ячейки в зависимости от значения | DataGrid change cell color based on value

Dacă Total Rămas va fi negativ atunci background să fie roșu


MainWindow.xaml

<Window x:Name="Form" x:Class="BIO_WPF.MainWindow" 
        Activated="Form_Activated"
        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:BIO_WPF"
        xmlns:col ="clr-namespace:DataColor"
        mc:Ignorable="d"
         xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        Title="Smart Management" Height="600" Width="1400" ResizeMode="CanResizeWithGrip">
    <Window.Resources>
        <col:NameToBrushConverter x:Key="NameToBrushConverter"/>
    </Window.Resources>
<Grid>
            
<DataGrid Grid.Row="2"
Mouse.MouseUp="dataGrid1_MouseUp" Name="dataGrid1" FontFamily="Times New Roman" FontSize="15" VerticalAlignment="Stretch">

<DataGridTextColumn Header="Total Rămas" x:Name="TotalNecom" IsReadOnly="True" Binding="{Binding d_totalramas}" Visibility="Visible">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</DataGridTextColumn.CellStyle>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding d_totalramas, Converter={StaticResource NameToBrushConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>                                                              
</Grid>
</Window>

 ___
 
DataColor.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace DataColor
{
    public class NameToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string input = value as string;
            bool a = input.Contains("-");
          if (a)
                return Brushes.Red;
          else
                return DependencyProperty.UnsetValue;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}



Niciun comentariu: