Change DataGrid cell colour based on values











up vote
59
down vote

favorite
22












I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml



Style TargetType="DataGridCell"


but instead of selecting a cell only is selecting all row? What am I missing?










share|improve this question
























  • can you publish sample code for your scenario. That will help. BTW, one way is to bind the background property of your datagridcell with the value of that cell and use a converter (to convert from value to color).
    – publicgk
    Apr 5 '11 at 10:28















up vote
59
down vote

favorite
22












I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml



Style TargetType="DataGridCell"


but instead of selecting a cell only is selecting all row? What am I missing?










share|improve this question
























  • can you publish sample code for your scenario. That will help. BTW, one way is to bind the background property of your datagridcell with the value of that cell and use a converter (to convert from value to color).
    – publicgk
    Apr 5 '11 at 10:28













up vote
59
down vote

favorite
22









up vote
59
down vote

favorite
22






22





I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml



Style TargetType="DataGridCell"


but instead of selecting a cell only is selecting all row? What am I missing?










share|improve this question















I have got a WPF datagrid and I want diffrent cell colours according to values. I have got below code on my xaml



Style TargetType="DataGridCell"


but instead of selecting a cell only is selecting all row? What am I missing?







c# wpf xaml colors datagrid






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 25 '17 at 15:06









Askolein

1,87411529




1,87411529










asked Apr 5 '11 at 9:10









CPM

3473714




3473714












  • can you publish sample code for your scenario. That will help. BTW, one way is to bind the background property of your datagridcell with the value of that cell and use a converter (to convert from value to color).
    – publicgk
    Apr 5 '11 at 10:28


















  • can you publish sample code for your scenario. That will help. BTW, one way is to bind the background property of your datagridcell with the value of that cell and use a converter (to convert from value to color).
    – publicgk
    Apr 5 '11 at 10:28
















can you publish sample code for your scenario. That will help. BTW, one way is to bind the background property of your datagridcell with the value of that cell and use a converter (to convert from value to color).
– publicgk
Apr 5 '11 at 10:28




can you publish sample code for your scenario. That will help. BTW, one way is to bind the background property of your datagridcell with the value of that cell and use a converter (to convert from value to color).
– publicgk
Apr 5 '11 at 10:28












7 Answers
7






active

oldest

votes

















up vote
125
down vote



accepted










If you try to set the DataGrid.CellStyle the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where the Name is John:



<DataGridTextColumn Binding="{Binding Name}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Text" Value="John">
<Setter Property="Background" Value="LightGreen"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>


A Screenshot





You could also use a ValueConverter to change the colour.



public class NameToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string input = value as string;
switch (input)
{
case "John":
return Brushes.LightGreen;
default:
return DependencyProperty.UnsetValue;
}
}

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


Usage:



<Window.Resources>
<local:NameToBrushConverter x:Key="NameToBrushConverter"/>
</Window.Resources>
...
<DataGridTextColumn Binding="{Binding Name}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>




Yet another option is to directly bind the Background to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.



e.g.



public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
OnPropertyChanged("NameBrush");
}
}
}

public Brush NameBrush
{
get
{
switch (Name)
{
case "John":
return Brushes.LightGreen;
default:
break;
}

return Brushes.Transparent;
}
}





share|improve this answer























  • hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
    – CPM
    Apr 5 '11 at 13:30










  • I do not quite understand what you mean...
    – H.B.
    Apr 5 '11 at 13:55






  • 1




    I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
    – CPM
    Apr 5 '11 at 14:34












  • There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
    – H.B.
    Apr 5 '11 at 15:07










  • I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
    – CPM
    Apr 5 '11 at 15:25




















up vote
15
down vote













If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.



C#



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

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


XAML



<UserControl.Resources>
<conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
<Style x:Key="CellStyle" TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>
</UserControl.Resources>
<DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
</DataGrid>





share|improve this answer





















  • Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
    – Moumit
    Dec 11 '17 at 21:28


















up vote
2
down vote













Just put instead



<Style TargetType="{x:DataGridCell}" >


But beware that this will target ALL your cells (you're aiming at all the objects of type DataGridCell )
If you want to put a style according to the cell type, I'd recommend you to use a DataTemplateSelector



A good example can be found in Christian Mosers' DataGrid tutorial:



http://www.wpftutorial.net/DataGrid.html#rowDetails



Have fun :)






share|improve this answer





















  • Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
    – CPM
    Apr 5 '11 at 9:45












  • Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
    – Damascus
    Apr 5 '11 at 12:37










  • no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
    – CPM
    Apr 5 '11 at 13:10


















up vote
2
down vote













In my case convertor must return string value. I don't why, but it works.



*.xaml (common style file, which is included in another xaml files)



<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>


*.cs



public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
return "#" + color.Name;
}





share|improve this answer






























    up vote
    2
    down vote













    This may be of help to you. It isn't the stock WPF datagrid however.



    I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.



    Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.



    Example



    Viewmodel.cs



    namespace ViewModel
    {
    [POCOViewModel]
    public class Table2DViewModel
    {
    public ITable2DView Table2DView { get; set; }

    public DataTable ItemsTable { get; set; }


    public Table2DViewModel()
    {
    }

    public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
    {
    Table2DView = table2DView;
    CreateTable();
    }

    private void CreateTable()
    {
    var dt = new DataTable();
    var xAxisStrings = new string{"X1","X2","X3"};
    var yAxisStrings = new string{"Y1","Y2","Y3"};

    //TODO determine your min, max number for your colours
    var minValue = 0;
    var maxValue = 100;
    Table2DView.SetColorFormatter(minValue,maxValue, null);

    //Add the columns
    dt.Columns.Add(" ", typeof(string));
    foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

    //Add all the values
    double z = 0;
    for (var y = 0; y < yAxisStrings.Length; y++)
    {
    var dr = dt.NewRow();
    dr[" "] = yAxisStrings[y];
    for (var x = 0; x < xAxisStrings.Length; x++)
    {
    //TODO put your actual values here!
    dr[xAxisStrings[x]] = z++; //Add a random values
    }
    dt.Rows.Add(dr);
    }
    ItemsTable = dt;
    }


    public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
    {
    var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
    return factory(mainViewModel, table2DView);
    }
    }

    }


    IView.cs



    namespace Interfaces
    {
    public interface ITable2DView
    {
    void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
    }
    }


    View.xaml.cs



    namespace View
    {
    public partial class Table2DView : ITable2DView
    {
    public Table2DView()
    {
    InitializeComponent();
    }

    static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
    {
    ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
    ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
    ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
    };

    public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
    {
    if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
    ConditionBehavior.MinValue = minValue;
    ConditionBehavior.MaxValue = maxValue;
    ConditionBehavior.ColorScaleFormat = colorScaleFormat;
    }
    }
    }


    DynamicConditionBehavior.cs



    namespace Behaviors
    {
    public class DynamicConditionBehavior : Behavior<GridControl>
    {
    GridControl Grid => AssociatedObject;

    protected override void OnAttached()
    {
    base.OnAttached();
    Grid.ItemsSourceChanged += OnItemsSourceChanged;
    }

    protected override void OnDetaching()
    {
    Grid.ItemsSourceChanged -= OnItemsSourceChanged;
    base.OnDetaching();
    }

    public ColorScaleFormat ColorScaleFormat { get; set;}
    public float MinValue { get; set; }
    public float MaxValue { get; set; }

    private void OnItemsSourceChanged(object sender, EventArgs e)
    {
    var view = Grid.View as TableView;

    if (view == null) return;

    view.FormatConditions.Clear();

    foreach (var col in Grid.Columns)
    {
    view.FormatConditions.Add(new ColorScaleFormatCondition
    {
    MinValue = MinValue,
    MaxValue = MaxValue,
    FieldName = col.FieldName,
    Format = ColorScaleFormat,
    });
    }

    }
    }
    }


    View.xaml



    <UserControl x:Class="View"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
    xmlns:ViewModels="clr-namespace:ViewModel"
    xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
    xmlns:behaviors="clr-namespace:Behaviors"
    xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
    DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
    mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

    <UserControl.Resources>
    <Style TargetType="{x:Type dxg:GridColumn}">
    <Setter Property="Width" Value="50"/>
    <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
    </Style>

    <Style TargetType="{x:Type dxg:HeaderItemsControl}">
    <Setter Property="FontWeight" Value="DemiBold"/>
    </Style>
    </UserControl.Resources>

    <!--<dxmvvm:Interaction.Behaviors>
    <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
    </dxmvvm:Interaction.Behaviors>-->
    <dxg:GridControl ItemsSource="{Binding ItemsTable}"
    AutoGenerateColumns="AddNew"
    EnableSmartColumnsGeneration="True">

    <dxmvvm:Interaction.Behaviors >
    <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
    </dxmvvm:Interaction.Behaviors>
    <dxg:GridControl.View>
    <dxg:TableView ShowGroupPanel="False"
    AllowPerPixelScrolling="True"/>
    </dxg:GridControl.View>
    </dxg:GridControl>
    </UserControl>





    share|improve this answer




























      up vote
      1
      down vote













              // Example: Adding a converter to a column (C#)
      Style styleReading = new Style(typeof(TextBlock));
      Setter s = new Setter();
      s.Property = TextBlock.ForegroundProperty;
      Binding b = new Binding();
      b.RelativeSource = RelativeSource.Self;
      b.Path = new PropertyPath(TextBlock.TextProperty);
      b.Converter = new ReadingForegroundSetter();
      s.Value = b;
      styleReading.Setters.Add(s);
      col.ElementStyle = styleReading;





      share|improve this answer





















      • i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
        – Vivek Parikh
        Apr 22 '13 at 10:55










      • Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
        – MickyD
        Nov 19 '15 at 7:25


















      up vote
      -1
      down vote













      To do this in the Code Behind (VB.NET)



      Dim txtCol As New DataGridTextColumn

      Dim style As New Style(GetType(TextBlock))
      Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
      tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
      style.Triggers.Add(tri)

      xtCol.ElementStyle = style





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5549617%2fchange-datagrid-cell-colour-based-on-values%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        7 Answers
        7






        active

        oldest

        votes








        7 Answers
        7






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        125
        down vote



        accepted










        If you try to set the DataGrid.CellStyle the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where the Name is John:



        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
        <Trigger Property="Text" Value="John">
        <Setter Property="Background" Value="LightGreen"/>
        </Trigger>
        </Style.Triggers>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>


        A Screenshot





        You could also use a ValueConverter to change the colour.



        public class NameToBrushConverter : IValueConverter
        {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        string input = value as string;
        switch (input)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        return DependencyProperty.UnsetValue;
        }
        }

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


        Usage:



        <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
        </Window.Resources>
        ...
        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>




        Yet another option is to directly bind the Background to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.



        e.g.



        public string Name
        {
        get { return _name; }
        set
        {
        if (_name != value)
        {
        _name = value;
        OnPropertyChanged("Name");
        OnPropertyChanged("NameBrush");
        }
        }
        }

        public Brush NameBrush
        {
        get
        {
        switch (Name)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        break;
        }

        return Brushes.Transparent;
        }
        }





        share|improve this answer























        • hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
          – CPM
          Apr 5 '11 at 13:30










        • I do not quite understand what you mean...
          – H.B.
          Apr 5 '11 at 13:55






        • 1




          I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
          – CPM
          Apr 5 '11 at 14:34












        • There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
          – H.B.
          Apr 5 '11 at 15:07










        • I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
          – CPM
          Apr 5 '11 at 15:25

















        up vote
        125
        down vote



        accepted










        If you try to set the DataGrid.CellStyle the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where the Name is John:



        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
        <Trigger Property="Text" Value="John">
        <Setter Property="Background" Value="LightGreen"/>
        </Trigger>
        </Style.Triggers>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>


        A Screenshot





        You could also use a ValueConverter to change the colour.



        public class NameToBrushConverter : IValueConverter
        {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        string input = value as string;
        switch (input)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        return DependencyProperty.UnsetValue;
        }
        }

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


        Usage:



        <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
        </Window.Resources>
        ...
        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>




        Yet another option is to directly bind the Background to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.



        e.g.



        public string Name
        {
        get { return _name; }
        set
        {
        if (_name != value)
        {
        _name = value;
        OnPropertyChanged("Name");
        OnPropertyChanged("NameBrush");
        }
        }
        }

        public Brush NameBrush
        {
        get
        {
        switch (Name)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        break;
        }

        return Brushes.Transparent;
        }
        }





        share|improve this answer























        • hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
          – CPM
          Apr 5 '11 at 13:30










        • I do not quite understand what you mean...
          – H.B.
          Apr 5 '11 at 13:55






        • 1




          I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
          – CPM
          Apr 5 '11 at 14:34












        • There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
          – H.B.
          Apr 5 '11 at 15:07










        • I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
          – CPM
          Apr 5 '11 at 15:25















        up vote
        125
        down vote



        accepted







        up vote
        125
        down vote



        accepted






        If you try to set the DataGrid.CellStyle the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where the Name is John:



        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
        <Trigger Property="Text" Value="John">
        <Setter Property="Background" Value="LightGreen"/>
        </Trigger>
        </Style.Triggers>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>


        A Screenshot





        You could also use a ValueConverter to change the colour.



        public class NameToBrushConverter : IValueConverter
        {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        string input = value as string;
        switch (input)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        return DependencyProperty.UnsetValue;
        }
        }

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


        Usage:



        <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
        </Window.Resources>
        ...
        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>




        Yet another option is to directly bind the Background to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.



        e.g.



        public string Name
        {
        get { return _name; }
        set
        {
        if (_name != value)
        {
        _name = value;
        OnPropertyChanged("Name");
        OnPropertyChanged("NameBrush");
        }
        }
        }

        public Brush NameBrush
        {
        get
        {
        switch (Name)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        break;
        }

        return Brushes.Transparent;
        }
        }





        share|improve this answer














        If you try to set the DataGrid.CellStyle the DataContext will be the row, so if you want to change the colour based on one cell it might be easiest to do so in specific columns, especially since columns can have varying contents, like TextBlocks, ComboBoxes and CheckBoxes. Here is an example of setting all the cells light-green where the Name is John:



        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
        <Trigger Property="Text" Value="John">
        <Setter Property="Background" Value="LightGreen"/>
        </Trigger>
        </Style.Triggers>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>


        A Screenshot





        You could also use a ValueConverter to change the colour.



        public class NameToBrushConverter : IValueConverter
        {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        string input = value as string;
        switch (input)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        return DependencyProperty.UnsetValue;
        }
        }

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


        Usage:



        <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
        </Window.Resources>
        ...
        <DataGridTextColumn Binding="{Binding Name}">
        <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
        </Style>
        </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>




        Yet another option is to directly bind the Background to a property which returns the respectively coloured brush. You will have to fire property change notifications in the setters of properties on which the colour is dependent.



        e.g.



        public string Name
        {
        get { return _name; }
        set
        {
        if (_name != value)
        {
        _name = value;
        OnPropertyChanged("Name");
        OnPropertyChanged("NameBrush");
        }
        }
        }

        public Brush NameBrush
        {
        get
        {
        switch (Name)
        {
        case "John":
        return Brushes.LightGreen;
        default:
        break;
        }

        return Brushes.Transparent;
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 20 '14 at 19:05

























        answered Apr 5 '11 at 12:42









        H.B.

        120k22237318




        120k22237318












        • hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
          – CPM
          Apr 5 '11 at 13:30










        • I do not quite understand what you mean...
          – H.B.
          Apr 5 '11 at 13:55






        • 1




          I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
          – CPM
          Apr 5 '11 at 14:34












        • There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
          – H.B.
          Apr 5 '11 at 15:07










        • I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
          – CPM
          Apr 5 '11 at 15:25




















        • hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
          – CPM
          Apr 5 '11 at 13:30










        • I do not quite understand what you mean...
          – H.B.
          Apr 5 '11 at 13:55






        • 1




          I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
          – CPM
          Apr 5 '11 at 14:34












        • There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
          – H.B.
          Apr 5 '11 at 15:07










        • I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
          – CPM
          Apr 5 '11 at 15:25


















        hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
        – CPM
        Apr 5 '11 at 13:30




        hi H.B,Thank you its more or less what I want , cell its changing but want to change depending on a value, have to look at value converter and connect with this code example that u sent me, but I think Its the right direction, have u got any example of what I am saying? Thank u
        – CPM
        Apr 5 '11 at 13:30












        I do not quite understand what you mean...
        – H.B.
        Apr 5 '11 at 13:55




        I do not quite understand what you mean...
        – H.B.
        Apr 5 '11 at 13:55




        1




        1




        I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
        – CPM
        Apr 5 '11 at 14:34






        I can have now a lightgreen color depending on a value of cell but want to do that with value converter, I dont want to define value="john" want to be triggered and setup color according to conditions that I ll set up programmatically(cs. file c#), Hope I am making my self clear.Thank u very much for helping me
        – CPM
        Apr 5 '11 at 14:34














        There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
        – H.B.
        Apr 5 '11 at 15:07




        There are tons of question on SO that illustrate how to use a value converter, you really could have done some searching. Edited my answer to show the equivalent value converter.
        – H.B.
        Apr 5 '11 at 15:07












        I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
        – CPM
        Apr 5 '11 at 15:25






        I have done that I acctually have one claa implemented already but it wasnt working properly thats why asked u, ** namespace GridCellColor { public class MyValueConverter : IValueConverter { #region IValueConverter Members object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){ if (Convert.ToInt32(value) > 0) return 10; else if (Convert.ToInt32(value) == 0) return 0; else return -1; } but wasnt working properly that Why I asked u if u have any examples anyway Thanks for your reply
        – CPM
        Apr 5 '11 at 15:25














        up vote
        15
        down vote













        If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.



        C#



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

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


        XAML



        <UserControl.Resources>
        <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
        <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
        </Style>
        </UserControl.Resources>
        <DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
        </DataGrid>





        share|improve this answer





















        • Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
          – Moumit
          Dec 11 '17 at 21:28















        up vote
        15
        down vote













        If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.



        C#



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

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


        XAML



        <UserControl.Resources>
        <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
        <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
        </Style>
        </UserControl.Resources>
        <DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
        </DataGrid>





        share|improve this answer





















        • Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
          – Moumit
          Dec 11 '17 at 21:28













        up vote
        15
        down vote










        up vote
        15
        down vote









        If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.



        C#



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

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


        XAML



        <UserControl.Resources>
        <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
        <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
        </Style>
        </UserControl.Resources>
        <DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
        </DataGrid>





        share|improve this answer












        If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.



        C#



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

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


        XAML



        <UserControl.Resources>
        <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
        <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
        </Style>
        </UserControl.Resources>
        <DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
        </DataGrid>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jul 12 '13 at 17:10









        unwrittenrainbow

        188313




        188313












        • Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
          – Moumit
          Dec 11 '17 at 21:28


















        • Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
          – Moumit
          Dec 11 '17 at 21:28
















        Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
        – Moumit
        Dec 11 '17 at 21:28




        Brushes.Red not helping but "#" + color.Name is. Idea is yours surely. Thanks
        – Moumit
        Dec 11 '17 at 21:28










        up vote
        2
        down vote













        Just put instead



        <Style TargetType="{x:DataGridCell}" >


        But beware that this will target ALL your cells (you're aiming at all the objects of type DataGridCell )
        If you want to put a style according to the cell type, I'd recommend you to use a DataTemplateSelector



        A good example can be found in Christian Mosers' DataGrid tutorial:



        http://www.wpftutorial.net/DataGrid.html#rowDetails



        Have fun :)






        share|improve this answer





















        • Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
          – CPM
          Apr 5 '11 at 9:45












        • Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
          – Damascus
          Apr 5 '11 at 12:37










        • no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
          – CPM
          Apr 5 '11 at 13:10















        up vote
        2
        down vote













        Just put instead



        <Style TargetType="{x:DataGridCell}" >


        But beware that this will target ALL your cells (you're aiming at all the objects of type DataGridCell )
        If you want to put a style according to the cell type, I'd recommend you to use a DataTemplateSelector



        A good example can be found in Christian Mosers' DataGrid tutorial:



        http://www.wpftutorial.net/DataGrid.html#rowDetails



        Have fun :)






        share|improve this answer





















        • Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
          – CPM
          Apr 5 '11 at 9:45












        • Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
          – Damascus
          Apr 5 '11 at 12:37










        • no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
          – CPM
          Apr 5 '11 at 13:10













        up vote
        2
        down vote










        up vote
        2
        down vote









        Just put instead



        <Style TargetType="{x:DataGridCell}" >


        But beware that this will target ALL your cells (you're aiming at all the objects of type DataGridCell )
        If you want to put a style according to the cell type, I'd recommend you to use a DataTemplateSelector



        A good example can be found in Christian Mosers' DataGrid tutorial:



        http://www.wpftutorial.net/DataGrid.html#rowDetails



        Have fun :)






        share|improve this answer












        Just put instead



        <Style TargetType="{x:DataGridCell}" >


        But beware that this will target ALL your cells (you're aiming at all the objects of type DataGridCell )
        If you want to put a style according to the cell type, I'd recommend you to use a DataTemplateSelector



        A good example can be found in Christian Mosers' DataGrid tutorial:



        http://www.wpftutorial.net/DataGrid.html#rowDetails



        Have fun :)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 5 '11 at 9:35









        Damascus

        4,73452647




        4,73452647












        • Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
          – CPM
          Apr 5 '11 at 9:45












        • Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
          – Damascus
          Apr 5 '11 at 12:37










        • no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
          – CPM
          Apr 5 '11 at 13:10


















        • Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
          – CPM
          Apr 5 '11 at 9:45












        • Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
          – Damascus
          Apr 5 '11 at 12:37










        • no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
          – CPM
          Apr 5 '11 at 13:10
















        Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
        – CPM
        Apr 5 '11 at 9:45






        Hi Damascus, Thanks for your reply, I Have TargetType of DatagridCell,You are right because its affecticting my enire row. I want only one cell to be affected depending on value of that cell. How can I do that?
        – CPM
        Apr 5 '11 at 9:45














        Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
        – Damascus
        Apr 5 '11 at 12:37




        Actually it depends on your case. Did you see the example on the link I gave you? There is a quite clear example on how to choose the style according to the object type (in the example: boy or girl). Is your problem similar?
        – Damascus
        Apr 5 '11 at 12:37












        no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
        – CPM
        Apr 5 '11 at 13:10




        no its not similar beacuse I want hust a single cell to be selected and not entire row as its is sown in example.
        – CPM
        Apr 5 '11 at 13:10










        up vote
        2
        down vote













        In my case convertor must return string value. I don't why, but it works.



        *.xaml (common style file, which is included in another xaml files)



        <Style TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
        </Style>


        *.cs



        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
        Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
        return "#" + color.Name;
        }





        share|improve this answer



























          up vote
          2
          down vote













          In my case convertor must return string value. I don't why, but it works.



          *.xaml (common style file, which is included in another xaml files)



          <Style TargetType="DataGridCell">
          <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
          </Style>


          *.cs



          public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
          {
          Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
          return "#" + color.Name;
          }





          share|improve this answer

























            up vote
            2
            down vote










            up vote
            2
            down vote









            In my case convertor must return string value. I don't why, but it works.



            *.xaml (common style file, which is included in another xaml files)



            <Style TargetType="DataGridCell">
            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
            </Style>


            *.cs



            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
            Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
            return "#" + color.Name;
            }





            share|improve this answer














            In my case convertor must return string value. I don't why, but it works.



            *.xaml (common style file, which is included in another xaml files)



            <Style TargetType="DataGridCell">
            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
            </Style>


            *.cs



            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
            Color color = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
            return "#" + color.Name;
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 29 '16 at 20:04

























            answered Sep 29 '16 at 11:27









            rinatdobr

            8619




            8619






















                up vote
                2
                down vote













                This may be of help to you. It isn't the stock WPF datagrid however.



                I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.



                Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.



                Example



                Viewmodel.cs



                namespace ViewModel
                {
                [POCOViewModel]
                public class Table2DViewModel
                {
                public ITable2DView Table2DView { get; set; }

                public DataTable ItemsTable { get; set; }


                public Table2DViewModel()
                {
                }

                public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
                {
                Table2DView = table2DView;
                CreateTable();
                }

                private void CreateTable()
                {
                var dt = new DataTable();
                var xAxisStrings = new string{"X1","X2","X3"};
                var yAxisStrings = new string{"Y1","Y2","Y3"};

                //TODO determine your min, max number for your colours
                var minValue = 0;
                var maxValue = 100;
                Table2DView.SetColorFormatter(minValue,maxValue, null);

                //Add the columns
                dt.Columns.Add(" ", typeof(string));
                foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

                //Add all the values
                double z = 0;
                for (var y = 0; y < yAxisStrings.Length; y++)
                {
                var dr = dt.NewRow();
                dr[" "] = yAxisStrings[y];
                for (var x = 0; x < xAxisStrings.Length; x++)
                {
                //TODO put your actual values here!
                dr[xAxisStrings[x]] = z++; //Add a random values
                }
                dt.Rows.Add(dr);
                }
                ItemsTable = dt;
                }


                public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
                {
                var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
                return factory(mainViewModel, table2DView);
                }
                }

                }


                IView.cs



                namespace Interfaces
                {
                public interface ITable2DView
                {
                void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
                }
                }


                View.xaml.cs



                namespace View
                {
                public partial class Table2DView : ITable2DView
                {
                public Table2DView()
                {
                InitializeComponent();
                }

                static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
                {
                ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
                ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
                ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
                };

                public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
                {
                if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
                ConditionBehavior.MinValue = minValue;
                ConditionBehavior.MaxValue = maxValue;
                ConditionBehavior.ColorScaleFormat = colorScaleFormat;
                }
                }
                }


                DynamicConditionBehavior.cs



                namespace Behaviors
                {
                public class DynamicConditionBehavior : Behavior<GridControl>
                {
                GridControl Grid => AssociatedObject;

                protected override void OnAttached()
                {
                base.OnAttached();
                Grid.ItemsSourceChanged += OnItemsSourceChanged;
                }

                protected override void OnDetaching()
                {
                Grid.ItemsSourceChanged -= OnItemsSourceChanged;
                base.OnDetaching();
                }

                public ColorScaleFormat ColorScaleFormat { get; set;}
                public float MinValue { get; set; }
                public float MaxValue { get; set; }

                private void OnItemsSourceChanged(object sender, EventArgs e)
                {
                var view = Grid.View as TableView;

                if (view == null) return;

                view.FormatConditions.Clear();

                foreach (var col in Grid.Columns)
                {
                view.FormatConditions.Add(new ColorScaleFormatCondition
                {
                MinValue = MinValue,
                MaxValue = MaxValue,
                FieldName = col.FieldName,
                Format = ColorScaleFormat,
                });
                }

                }
                }
                }


                View.xaml



                <UserControl x:Class="View"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
                xmlns:ViewModels="clr-namespace:ViewModel"
                xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
                xmlns:behaviors="clr-namespace:Behaviors"
                xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
                DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
                mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

                <UserControl.Resources>
                <Style TargetType="{x:Type dxg:GridColumn}">
                <Setter Property="Width" Value="50"/>
                <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
                </Style>

                <Style TargetType="{x:Type dxg:HeaderItemsControl}">
                <Setter Property="FontWeight" Value="DemiBold"/>
                </Style>
                </UserControl.Resources>

                <!--<dxmvvm:Interaction.Behaviors>
                <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
                </dxmvvm:Interaction.Behaviors>-->
                <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                AutoGenerateColumns="AddNew"
                EnableSmartColumnsGeneration="True">

                <dxmvvm:Interaction.Behaviors >
                <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
                </dxmvvm:Interaction.Behaviors>
                <dxg:GridControl.View>
                <dxg:TableView ShowGroupPanel="False"
                AllowPerPixelScrolling="True"/>
                </dxg:GridControl.View>
                </dxg:GridControl>
                </UserControl>





                share|improve this answer

























                  up vote
                  2
                  down vote













                  This may be of help to you. It isn't the stock WPF datagrid however.



                  I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.



                  Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.



                  Example



                  Viewmodel.cs



                  namespace ViewModel
                  {
                  [POCOViewModel]
                  public class Table2DViewModel
                  {
                  public ITable2DView Table2DView { get; set; }

                  public DataTable ItemsTable { get; set; }


                  public Table2DViewModel()
                  {
                  }

                  public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
                  {
                  Table2DView = table2DView;
                  CreateTable();
                  }

                  private void CreateTable()
                  {
                  var dt = new DataTable();
                  var xAxisStrings = new string{"X1","X2","X3"};
                  var yAxisStrings = new string{"Y1","Y2","Y3"};

                  //TODO determine your min, max number for your colours
                  var minValue = 0;
                  var maxValue = 100;
                  Table2DView.SetColorFormatter(minValue,maxValue, null);

                  //Add the columns
                  dt.Columns.Add(" ", typeof(string));
                  foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

                  //Add all the values
                  double z = 0;
                  for (var y = 0; y < yAxisStrings.Length; y++)
                  {
                  var dr = dt.NewRow();
                  dr[" "] = yAxisStrings[y];
                  for (var x = 0; x < xAxisStrings.Length; x++)
                  {
                  //TODO put your actual values here!
                  dr[xAxisStrings[x]] = z++; //Add a random values
                  }
                  dt.Rows.Add(dr);
                  }
                  ItemsTable = dt;
                  }


                  public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
                  {
                  var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
                  return factory(mainViewModel, table2DView);
                  }
                  }

                  }


                  IView.cs



                  namespace Interfaces
                  {
                  public interface ITable2DView
                  {
                  void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
                  }
                  }


                  View.xaml.cs



                  namespace View
                  {
                  public partial class Table2DView : ITable2DView
                  {
                  public Table2DView()
                  {
                  InitializeComponent();
                  }

                  static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
                  {
                  ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
                  ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
                  ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
                  };

                  public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
                  {
                  if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
                  ConditionBehavior.MinValue = minValue;
                  ConditionBehavior.MaxValue = maxValue;
                  ConditionBehavior.ColorScaleFormat = colorScaleFormat;
                  }
                  }
                  }


                  DynamicConditionBehavior.cs



                  namespace Behaviors
                  {
                  public class DynamicConditionBehavior : Behavior<GridControl>
                  {
                  GridControl Grid => AssociatedObject;

                  protected override void OnAttached()
                  {
                  base.OnAttached();
                  Grid.ItemsSourceChanged += OnItemsSourceChanged;
                  }

                  protected override void OnDetaching()
                  {
                  Grid.ItemsSourceChanged -= OnItemsSourceChanged;
                  base.OnDetaching();
                  }

                  public ColorScaleFormat ColorScaleFormat { get; set;}
                  public float MinValue { get; set; }
                  public float MaxValue { get; set; }

                  private void OnItemsSourceChanged(object sender, EventArgs e)
                  {
                  var view = Grid.View as TableView;

                  if (view == null) return;

                  view.FormatConditions.Clear();

                  foreach (var col in Grid.Columns)
                  {
                  view.FormatConditions.Add(new ColorScaleFormatCondition
                  {
                  MinValue = MinValue,
                  MaxValue = MaxValue,
                  FieldName = col.FieldName,
                  Format = ColorScaleFormat,
                  });
                  }

                  }
                  }
                  }


                  View.xaml



                  <UserControl x:Class="View"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                  xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
                  xmlns:ViewModels="clr-namespace:ViewModel"
                  xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
                  xmlns:behaviors="clr-namespace:Behaviors"
                  xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
                  DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
                  mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

                  <UserControl.Resources>
                  <Style TargetType="{x:Type dxg:GridColumn}">
                  <Setter Property="Width" Value="50"/>
                  <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
                  </Style>

                  <Style TargetType="{x:Type dxg:HeaderItemsControl}">
                  <Setter Property="FontWeight" Value="DemiBold"/>
                  </Style>
                  </UserControl.Resources>

                  <!--<dxmvvm:Interaction.Behaviors>
                  <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
                  </dxmvvm:Interaction.Behaviors>-->
                  <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                  AutoGenerateColumns="AddNew"
                  EnableSmartColumnsGeneration="True">

                  <dxmvvm:Interaction.Behaviors >
                  <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
                  </dxmvvm:Interaction.Behaviors>
                  <dxg:GridControl.View>
                  <dxg:TableView ShowGroupPanel="False"
                  AllowPerPixelScrolling="True"/>
                  </dxg:GridControl.View>
                  </dxg:GridControl>
                  </UserControl>





                  share|improve this answer























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    This may be of help to you. It isn't the stock WPF datagrid however.



                    I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.



                    Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.



                    Example



                    Viewmodel.cs



                    namespace ViewModel
                    {
                    [POCOViewModel]
                    public class Table2DViewModel
                    {
                    public ITable2DView Table2DView { get; set; }

                    public DataTable ItemsTable { get; set; }


                    public Table2DViewModel()
                    {
                    }

                    public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
                    {
                    Table2DView = table2DView;
                    CreateTable();
                    }

                    private void CreateTable()
                    {
                    var dt = new DataTable();
                    var xAxisStrings = new string{"X1","X2","X3"};
                    var yAxisStrings = new string{"Y1","Y2","Y3"};

                    //TODO determine your min, max number for your colours
                    var minValue = 0;
                    var maxValue = 100;
                    Table2DView.SetColorFormatter(minValue,maxValue, null);

                    //Add the columns
                    dt.Columns.Add(" ", typeof(string));
                    foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

                    //Add all the values
                    double z = 0;
                    for (var y = 0; y < yAxisStrings.Length; y++)
                    {
                    var dr = dt.NewRow();
                    dr[" "] = yAxisStrings[y];
                    for (var x = 0; x < xAxisStrings.Length; x++)
                    {
                    //TODO put your actual values here!
                    dr[xAxisStrings[x]] = z++; //Add a random values
                    }
                    dt.Rows.Add(dr);
                    }
                    ItemsTable = dt;
                    }


                    public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
                    {
                    var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
                    return factory(mainViewModel, table2DView);
                    }
                    }

                    }


                    IView.cs



                    namespace Interfaces
                    {
                    public interface ITable2DView
                    {
                    void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
                    }
                    }


                    View.xaml.cs



                    namespace View
                    {
                    public partial class Table2DView : ITable2DView
                    {
                    public Table2DView()
                    {
                    InitializeComponent();
                    }

                    static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
                    {
                    ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
                    ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
                    ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
                    };

                    public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
                    {
                    if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
                    ConditionBehavior.MinValue = minValue;
                    ConditionBehavior.MaxValue = maxValue;
                    ConditionBehavior.ColorScaleFormat = colorScaleFormat;
                    }
                    }
                    }


                    DynamicConditionBehavior.cs



                    namespace Behaviors
                    {
                    public class DynamicConditionBehavior : Behavior<GridControl>
                    {
                    GridControl Grid => AssociatedObject;

                    protected override void OnAttached()
                    {
                    base.OnAttached();
                    Grid.ItemsSourceChanged += OnItemsSourceChanged;
                    }

                    protected override void OnDetaching()
                    {
                    Grid.ItemsSourceChanged -= OnItemsSourceChanged;
                    base.OnDetaching();
                    }

                    public ColorScaleFormat ColorScaleFormat { get; set;}
                    public float MinValue { get; set; }
                    public float MaxValue { get; set; }

                    private void OnItemsSourceChanged(object sender, EventArgs e)
                    {
                    var view = Grid.View as TableView;

                    if (view == null) return;

                    view.FormatConditions.Clear();

                    foreach (var col in Grid.Columns)
                    {
                    view.FormatConditions.Add(new ColorScaleFormatCondition
                    {
                    MinValue = MinValue,
                    MaxValue = MaxValue,
                    FieldName = col.FieldName,
                    Format = ColorScaleFormat,
                    });
                    }

                    }
                    }
                    }


                    View.xaml



                    <UserControl x:Class="View"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
                    xmlns:ViewModels="clr-namespace:ViewModel"
                    xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
                    xmlns:behaviors="clr-namespace:Behaviors"
                    xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
                    DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
                    mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

                    <UserControl.Resources>
                    <Style TargetType="{x:Type dxg:GridColumn}">
                    <Setter Property="Width" Value="50"/>
                    <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
                    </Style>

                    <Style TargetType="{x:Type dxg:HeaderItemsControl}">
                    <Setter Property="FontWeight" Value="DemiBold"/>
                    </Style>
                    </UserControl.Resources>

                    <!--<dxmvvm:Interaction.Behaviors>
                    <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
                    </dxmvvm:Interaction.Behaviors>-->
                    <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                    AutoGenerateColumns="AddNew"
                    EnableSmartColumnsGeneration="True">

                    <dxmvvm:Interaction.Behaviors >
                    <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
                    </dxmvvm:Interaction.Behaviors>
                    <dxg:GridControl.View>
                    <dxg:TableView ShowGroupPanel="False"
                    AllowPerPixelScrolling="True"/>
                    </dxg:GridControl.View>
                    </dxg:GridControl>
                    </UserControl>





                    share|improve this answer












                    This may be of help to you. It isn't the stock WPF datagrid however.



                    I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.



                    Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.



                    Example



                    Viewmodel.cs



                    namespace ViewModel
                    {
                    [POCOViewModel]
                    public class Table2DViewModel
                    {
                    public ITable2DView Table2DView { get; set; }

                    public DataTable ItemsTable { get; set; }


                    public Table2DViewModel()
                    {
                    }

                    public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
                    {
                    Table2DView = table2DView;
                    CreateTable();
                    }

                    private void CreateTable()
                    {
                    var dt = new DataTable();
                    var xAxisStrings = new string{"X1","X2","X3"};
                    var yAxisStrings = new string{"Y1","Y2","Y3"};

                    //TODO determine your min, max number for your colours
                    var minValue = 0;
                    var maxValue = 100;
                    Table2DView.SetColorFormatter(minValue,maxValue, null);

                    //Add the columns
                    dt.Columns.Add(" ", typeof(string));
                    foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

                    //Add all the values
                    double z = 0;
                    for (var y = 0; y < yAxisStrings.Length; y++)
                    {
                    var dr = dt.NewRow();
                    dr[" "] = yAxisStrings[y];
                    for (var x = 0; x < xAxisStrings.Length; x++)
                    {
                    //TODO put your actual values here!
                    dr[xAxisStrings[x]] = z++; //Add a random values
                    }
                    dt.Rows.Add(dr);
                    }
                    ItemsTable = dt;
                    }


                    public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
                    {
                    var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
                    return factory(mainViewModel, table2DView);
                    }
                    }

                    }


                    IView.cs



                    namespace Interfaces
                    {
                    public interface ITable2DView
                    {
                    void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
                    }
                    }


                    View.xaml.cs



                    namespace View
                    {
                    public partial class Table2DView : ITable2DView
                    {
                    public Table2DView()
                    {
                    InitializeComponent();
                    }

                    static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
                    {
                    ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
                    ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
                    ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
                    };

                    public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
                    {
                    if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
                    ConditionBehavior.MinValue = minValue;
                    ConditionBehavior.MaxValue = maxValue;
                    ConditionBehavior.ColorScaleFormat = colorScaleFormat;
                    }
                    }
                    }


                    DynamicConditionBehavior.cs



                    namespace Behaviors
                    {
                    public class DynamicConditionBehavior : Behavior<GridControl>
                    {
                    GridControl Grid => AssociatedObject;

                    protected override void OnAttached()
                    {
                    base.OnAttached();
                    Grid.ItemsSourceChanged += OnItemsSourceChanged;
                    }

                    protected override void OnDetaching()
                    {
                    Grid.ItemsSourceChanged -= OnItemsSourceChanged;
                    base.OnDetaching();
                    }

                    public ColorScaleFormat ColorScaleFormat { get; set;}
                    public float MinValue { get; set; }
                    public float MaxValue { get; set; }

                    private void OnItemsSourceChanged(object sender, EventArgs e)
                    {
                    var view = Grid.View as TableView;

                    if (view == null) return;

                    view.FormatConditions.Clear();

                    foreach (var col in Grid.Columns)
                    {
                    view.FormatConditions.Add(new ColorScaleFormatCondition
                    {
                    MinValue = MinValue,
                    MaxValue = MaxValue,
                    FieldName = col.FieldName,
                    Format = ColorScaleFormat,
                    });
                    }

                    }
                    }
                    }


                    View.xaml



                    <UserControl x:Class="View"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
                    xmlns:ViewModels="clr-namespace:ViewModel"
                    xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
                    xmlns:behaviors="clr-namespace:Behaviors"
                    xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
                    DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
                    mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

                    <UserControl.Resources>
                    <Style TargetType="{x:Type dxg:GridColumn}">
                    <Setter Property="Width" Value="50"/>
                    <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
                    </Style>

                    <Style TargetType="{x:Type dxg:HeaderItemsControl}">
                    <Setter Property="FontWeight" Value="DemiBold"/>
                    </Style>
                    </UserControl.Resources>

                    <!--<dxmvvm:Interaction.Behaviors>
                    <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
                    </dxmvvm:Interaction.Behaviors>-->
                    <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                    AutoGenerateColumns="AddNew"
                    EnableSmartColumnsGeneration="True">

                    <dxmvvm:Interaction.Behaviors >
                    <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
                    </dxmvvm:Interaction.Behaviors>
                    <dxg:GridControl.View>
                    <dxg:TableView ShowGroupPanel="False"
                    AllowPerPixelScrolling="True"/>
                    </dxg:GridControl.View>
                    </dxg:GridControl>
                    </UserControl>






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 19 '16 at 0:35









                    rolls

                    91331334




                    91331334






















                        up vote
                        1
                        down vote













                                // Example: Adding a converter to a column (C#)
                        Style styleReading = new Style(typeof(TextBlock));
                        Setter s = new Setter();
                        s.Property = TextBlock.ForegroundProperty;
                        Binding b = new Binding();
                        b.RelativeSource = RelativeSource.Self;
                        b.Path = new PropertyPath(TextBlock.TextProperty);
                        b.Converter = new ReadingForegroundSetter();
                        s.Value = b;
                        styleReading.Setters.Add(s);
                        col.ElementStyle = styleReading;





                        share|improve this answer





















                        • i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
                          – Vivek Parikh
                          Apr 22 '13 at 10:55










                        • Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
                          – MickyD
                          Nov 19 '15 at 7:25















                        up vote
                        1
                        down vote













                                // Example: Adding a converter to a column (C#)
                        Style styleReading = new Style(typeof(TextBlock));
                        Setter s = new Setter();
                        s.Property = TextBlock.ForegroundProperty;
                        Binding b = new Binding();
                        b.RelativeSource = RelativeSource.Self;
                        b.Path = new PropertyPath(TextBlock.TextProperty);
                        b.Converter = new ReadingForegroundSetter();
                        s.Value = b;
                        styleReading.Setters.Add(s);
                        col.ElementStyle = styleReading;





                        share|improve this answer





















                        • i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
                          – Vivek Parikh
                          Apr 22 '13 at 10:55










                        • Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
                          – MickyD
                          Nov 19 '15 at 7:25













                        up vote
                        1
                        down vote










                        up vote
                        1
                        down vote









                                // Example: Adding a converter to a column (C#)
                        Style styleReading = new Style(typeof(TextBlock));
                        Setter s = new Setter();
                        s.Property = TextBlock.ForegroundProperty;
                        Binding b = new Binding();
                        b.RelativeSource = RelativeSource.Self;
                        b.Path = new PropertyPath(TextBlock.TextProperty);
                        b.Converter = new ReadingForegroundSetter();
                        s.Value = b;
                        styleReading.Setters.Add(s);
                        col.ElementStyle = styleReading;





                        share|improve this answer












                                // Example: Adding a converter to a column (C#)
                        Style styleReading = new Style(typeof(TextBlock));
                        Setter s = new Setter();
                        s.Property = TextBlock.ForegroundProperty;
                        Binding b = new Binding();
                        b.RelativeSource = RelativeSource.Self;
                        b.Path = new PropertyPath(TextBlock.TextProperty);
                        b.Converter = new ReadingForegroundSetter();
                        s.Value = b;
                        styleReading.Setters.Add(s);
                        col.ElementStyle = styleReading;






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 27 '13 at 9:34









                        user2015238

                        191




                        191












                        • i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
                          – Vivek Parikh
                          Apr 22 '13 at 10:55










                        • Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
                          – MickyD
                          Nov 19 '15 at 7:25


















                        • i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
                          – Vivek Parikh
                          Apr 22 '13 at 10:55










                        • Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
                          – MickyD
                          Nov 19 '15 at 7:25
















                        i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
                        – Vivek Parikh
                        Apr 22 '13 at 10:55




                        i want it to be done at run time . i am binding datagrid with datatable on window load.so how can it be done?
                        – Vivek Parikh
                        Apr 22 '13 at 10:55












                        Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
                        – MickyD
                        Nov 19 '15 at 7:25




                        Consider improving your answer. Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day
                        – MickyD
                        Nov 19 '15 at 7:25










                        up vote
                        -1
                        down vote













                        To do this in the Code Behind (VB.NET)



                        Dim txtCol As New DataGridTextColumn

                        Dim style As New Style(GetType(TextBlock))
                        Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
                        tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
                        style.Triggers.Add(tri)

                        xtCol.ElementStyle = style





                        share|improve this answer



























                          up vote
                          -1
                          down vote













                          To do this in the Code Behind (VB.NET)



                          Dim txtCol As New DataGridTextColumn

                          Dim style As New Style(GetType(TextBlock))
                          Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
                          tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
                          style.Triggers.Add(tri)

                          xtCol.ElementStyle = style





                          share|improve this answer

























                            up vote
                            -1
                            down vote










                            up vote
                            -1
                            down vote









                            To do this in the Code Behind (VB.NET)



                            Dim txtCol As New DataGridTextColumn

                            Dim style As New Style(GetType(TextBlock))
                            Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
                            tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
                            style.Triggers.Add(tri)

                            xtCol.ElementStyle = style





                            share|improve this answer














                            To do this in the Code Behind (VB.NET)



                            Dim txtCol As New DataGridTextColumn

                            Dim style As New Style(GetType(TextBlock))
                            Dim tri As New Trigger With {.Property = TextBlock.TextProperty, .Value = "John"}
                            tri.Setters.Add(New Setter With {.Property = TextBlock.BackgroundProperty, .Value = Brushes.Green})
                            style.Triggers.Add(tri)

                            xtCol.ElementStyle = style






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Sep 28 '12 at 18:09









                            Conrad Frix

                            45.1k1170120




                            45.1k1170120










                            answered Aug 9 '12 at 14:54









                            Cassio Borghi

                            11




                            11






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5549617%2fchange-datagrid-cell-colour-based-on-values%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Tangent Lines Diagram Along Smooth Curve

                                Yusuf al-Mu'taman ibn Hud

                                Zucchini