简体   繁体   English

c#更改datagrid单元格颜色

[英]c# change datagrid cell color

i am trying to change color of a datagrid cell but only in c# not by xaml. 我正在尝试更改数据网格单元格的颜色,但仅限于c#而不是xaml。

<DataGrid x:Name="arcad_Grid"  HorizontalAlignment="Left" Height="252" Margin="822,138,0,0" VerticalAlignment="Top" Width="178" Loaded="getArcadVersion" AutoGenerateColumns="true" SelectionChanged="Choicecontrol" SelectionMode="Extended" CanUserAddRows="False" CanUserResizeColumns="False" CanUserResizeRows="False" SelectionUnit="Cell"  />

is there an other way of doing it via c#? 有没有其他方法通过c#做到这一点? any help would be appreciated 任何帮助,将不胜感激

Added the Whole part Getting the Data from the Database and filling it with the DataGrid 添加了整个部分从数据库获取数据并使用DataGrid填充它

   try
        {
            conn.Open();


            string cmd = "DSPOBJD OBJ(QSYS/DIID*) OBJTYPE(*LIB) OUTPUT(*OUTFILE) OUTFILE(Arcad_V)";
            OdbcConnection odbc = new OdbcConnection("DRIVER={Client Access ODBC Driver (32-bit)};SYSTEM=XXXX;TRANSLATE=1;XDYNAMIC=0;CONNTYPE=0;DBQ=XXXX;UID=XXXX;password=XXXX");

            string as400cmd = "CALL  QCMDEXC('" + cmd + "')";
            OdbcCommand odbcCommand = new OdbcCommand(as400cmd,odbc);
            odbc.Open();
            odbcCommand.ExecuteNonQuery();

            string SQLquery = "select ODOBNM,ODOBTP from Arcad_V ";
            iDB2Command comm = conn.CreateCommand();
            comm.CommandText = SQLquery;
            iDB2DataReader reader = comm.ExecuteReader();
            while (reader.Read())
            {
                arcad.createspoolfile(reader[0].ToString());
             if (arcad.couleur == "rouge")
                {
                    DataGridCell cell = GetCell(0,0,arcad_Grid);
                    cell.Background = new SolidColorBrush(Colors.Red);
                }
                if (arcad.couleur == "vert")
                {
                    DataGridCell cell = GetCell(0, 0, arcad_Grid);
                    cell.Background = new SolidColorBrush(Colors.Red);
                }

            }

            iDB2DataAdapter adp = new iDB2DataAdapter(SQLquery, conn);
            DataTable dt = new DataTable("DIIAB.Arcad_V");


            adp.Fill(dt);
            arcad_Grid.ItemsSource = dt.DefaultView;
            conn.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());

        }

I have created a new sample with some data: you have to use a converter with multibinding to do waht you want.. 我创建了一个包含一些数据的新示例:您必须使用具有多重绑定的转换器来执行您想要的操作。

mainwindows.xaml: mainwindows.xaml:

<Window x:Class="WpfApplication1.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:WpfApplication1="clr-namespace:WpfApplication1"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"

        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <WpfApplication1:HighlighterConverter x:Key="myHighlighterConverter" />
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="arcad_Grid" Loaded="arcad_Grid_Loaded" SelectionChanged="arcad_Grid_SelectionChanged" 
                  AutoGenerateColumns="True" SelectionUnit="Cell" >
            <DataGrid.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Setter Property="Background">
                        <Setter.Value>
                            <MultiBinding Converter="{StaticResource myHighlighterConverter}" >
                                <MultiBinding.Bindings>
                                    <Binding RelativeSource="{RelativeSource Self}"></Binding>
                                    <Binding Path="Row"></Binding>
                                </MultiBinding.Bindings>
                            </MultiBinding>
                        </Setter.Value>
                    </Setter>
                </Style>
            </DataGrid.CellStyle>
        </DataGrid>
    </Grid>
</Window>

during the loaded event in mainwindow.xaml.cs: 在mainwindow.xaml.cs中加载的事件期间:

    private void arcad_Grid_Loaded(object sender, RoutedEventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Color", typeof(string));

        // Here we add five DataRows.
        table.Rows.Add(25, "Indocin", "David", "rouge");
        table.Rows.Add(50, "Enebrel", "Sam", "vert");
        table.Rows.Add(10, "Hydralazine", "Christoff", "rouge");
        table.Rows.Add(21, "Combivent", "Janet", "vert");
        table.Rows.Add(100, "Dilantin", "Melanie", "vert");         

        arcad_Grid.ItemsSource = table.DefaultView;
    }

converter.cs: converter.cs:

using System;
using System.Data;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Controls;

namespace WpfApplication1
{
    public class HighlighterConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values[1] is DataRow)
            {
                var cell = (DataGridCell)values[0];
                var row = (DataRow)values[1];
                var columnName = cell.Column.SortMemberPath;

                if (row[columnName].ToString() == "rouge" )
                    return Brushes.Red;
                if (row[columnName].ToString() == "vert")
                    return Brushes.Green;

            }
            return SystemColors.AppWorkspaceColor;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }

}

在此输入图像描述

Another solution with a simple converter: you add this in converter.cs 使用简单转换器的另一种解决方案:在converter.cs中添加它

public class ValueToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input;
        try
        {
            DataGridCell dgc = (DataGridCell)value;
            System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
            input = (string)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
        }
        catch (InvalidCastException e)
        {
            return DependencyProperty.UnsetValue;
        }
        switch (input)
        {
            case "rouge": return Brushes.Red;
            case "vert": return Brushes.Green;
            default: return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

modification in mainwindow.xaml: 在mainwindow.xaml中修改:

<Window.Resources>
    <WpfApplication1:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
    </Style>
</Window.Resources>
<Grid>
    <DataGrid x:Name="arcad_Grid" Loaded="arcad_Grid_Loaded" SelectionChanged="arcad_Grid_SelectionChanged" 
              AutoGenerateColumns="True" SelectionUnit="Cell" CellStyle="{StaticResource CellStyle}" >           
    </DataGrid>
</Grid>

same result with less coding 编码较少的结果相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM