Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am facing issues while selecting a particular cell say 5th Row and 3rd Column.
In WPF I used a Property named Columns for Datagrid where I can select column for all rows but I need to get any random cell programatically to Set Cellstyle.

Please advise me to get rid of this issue.

What I have tried:

Used Column property for Datagrid
Posted
Updated 22-Jan-19 6:22am

Did you tried using ValueConverter for this. Use dependency property to perform calculation based on previous value and this should trigger binding converter where you should set the color. For cell coloring using converter, refer to below code:

XAML:

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


Code:

public class CellConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input = value as string;
        switch (input)
        {
            case <your value condition>:
                return Brushes.Red;
            default:
                return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
 
Share this answer
 
Use the DataGridTemplateColumn, and bind the Background color to an expression on your data source it. e.g.

C#
DataGridTemplateColumn Width="*">
               <DataGridTemplateColumn.CellTemplate>
                  <DataTemplate>
                     <TextBlock Text="{Binding Path=Text}"
                                Background="{Binding Path=BackgroundColor}"
                                TextWrapping="Wrap"
                                Padding="4" />
                  </DataTemplate>
               </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>


public SolidColorBrush BackgroundColor { get { 
   if ( this.PartNumber == 3 ) { 
      return Brushes.MistyRose; 
   } 
   return Brushes.Transparent; 
} }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900