Conditional row style on one grid with page that has multiple grids

Hi, I want to set a conditional row style for a grid on a page that has multiple grids.

I was looking at the example:

<ContentPage xmlns:syncfusion="http://schemas.syncfusion.com/maui">
    <ContentPage.Resources>
        <local:ColorConverter x:Key="converter"/>
        <Style TargetType="syncfusion:DataGridRow">
            <Setter Property="Background" Value="{Binding Converter={StaticResource converter}}" />
        </Style>
    </ContentPage.Resources>
</ContentPage>

But not sure how to apply this to only one grid.


9 Replies 1 reply marked as answer

TP Tamilarasan Paranthaman Syncfusion Team April 15, 2024 01:44 PM UTC

Hi Phunction,

As per your requirement, applying a style implicitly to a single DataGrid by setting TargetType is not feasible if the page contains multiple DataGrids.


However, you can achieve your goal within the current DataGrid implementation by setting the background color directly on the DataGrid cell. We have provided a sample for your reference, demonstrating the conditional cell style for a single DataGrid. Please review the following code snippet and sample file for detailed information.



For Auto Generating Column:


 

public partial class MainPage : ContentPage

 {

     public MainPage()

     {

         InitializeComponent();

         dataGrid2.AutoGeneratingColumn += DataGrid2_AutoGeneratingColumn;

     }

 

     private void DataGrid2_AutoGeneratingColumn(object? sender, DataGridAutoGeneratingColumnEventArgs e)

     {

         var dataGridCellStyle = new Style(typeof(DataGridCell));

 

         var setterBackground = new Setter

         {

             Property = DataGridCell.BackgroundProperty,

             Value = new Binding

             {

                 Path = "OrderID",

                 Converter = new ColorConverter()

             }

 

         };

 

 

         dataGridCellStyle.Setters.Add(setterBackground);

 

         e.Column.CellStyle = dataGridCellStyle;

     }

 }

 

 public class ColorConverter : IValueConverter

 {

     object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo info)

     {

         var input = (int)value;

         if (input < 1003)

             return Colors.Bisque;

         else if (input < 1007)

             return Colors.LightBlue;

         else

             return Colors.White;

     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

     {

         throw new NotImplementedException();

     }

 }

 

 

For Manual Columns:

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 

             xmlns:dataGrid="clr-namespace:Syncfusion.Maui.DataGrid;assembly=Syncfusion.Maui.DataGrid"

             xmlns:local="clr-namespace:SfDataGridSample"

             x:Class="SfDataGridSample.MainPage">

 

    <ContentPage.BindingContext>

        <local:OrderInfoRepository x:Name="ViewModel"/>

    </ContentPage.BindingContext>

 

    <ContentPage.Resources>

        <local:ColorConverter x:Key="converter"/>

        <Style x:Key="cellStyle" TargetType="dataGrid:DataGridCell">

            <Setter Property="Background" Value="{Binding Path=OrderID ,Converter={StaticResource converter}}" />

        </Style>

    </ContentPage.Resources>

 

    <StackLayout>

 

        <dataGrid:SfDataGrid x:Name="dataGrid1"

                             ItemsSource="{Binding OrderInfoCollection}">

            <dataGrid:SfDataGrid.Columns>

                <dataGrid:DataGridTextColumn MappingName="OrderID"

                                             CellStyle="{StaticResource cellStyle}"

                                             HeaderText="Order ID" />

                <dataGrid:DataGridTextColumn MappingName="CustomerID"

                                             CellStyle="{StaticResource cellStyle}"

                                             HeaderText="Customer ID" />

                <dataGrid:DataGridTextColumn MappingName="Customer"

                                             CellStyle="{StaticResource cellStyle}"

                                             HeaderText="Customer Name" />

                <dataGrid:DataGridTextColumn MappingName="ShipCity"

                                             CellStyle="{StaticResource cellStyle}"

                                             HeaderText="Ship City" />

                <dataGrid:DataGridTextColumn MappingName="ShipCountry"

                                             CellStyle="{StaticResource cellStyle}"

                                             HeaderText="Ship Country" />

                <dataGrid:DataGridTextColumn MappingName="Price"

                                             CellStyle="{StaticResource cellStyle}"

                                             HeaderText="Price" />

            </dataGrid:SfDataGrid.Columns>

        </dataGrid:SfDataGrid>

 

        <dataGrid:SfDataGrid x:Name="dataGrid2"

                             ItemsSource="{Binding OrderInfoCollection}">

        </dataGrid:SfDataGrid>

    </StackLayout>

</ContentPage>

 


Regards,

Tamilarasan


Attachment: Sample_9b8898ba.zip


PH Phunction April 15, 2024 08:54 PM UTC

How can I do this when adding columns programmatically, like this:

(I would like to change the entire row background color based on the value of one cell in that row)

Columns.Add(new DataGridTextColumn()

{

    MappingName = szMap,

    AllowEditing = bAllow,

    HeaderText = szName,

    HeaderTextAlignment = TextAlignment.Center,

    CellStyle = new Style(typeof(DataGridCell))


    {


        Setters =

        {

            new Setter

            {

                Property = DataGridCell.BackgroundProperty,

                Value = new SolidColorBrush(ColorRow(Columns.Count))

            }

        }


    }

});



TP Tamilarasan Paranthaman Syncfusion Team April 16, 2024 05:07 PM UTC

Phunction,


We have implemented a simple sample following the approach you described and have attached it for your reference. Please review the attached sample to gain a better understanding of the implementation. If you have any further questions or require additional assistance, feel free to reach out to us. As always, we will be happy to assist you.


Regards,

Tamilarasan


Attachment: Sample_fff3883f.zip


PH Phunction April 16, 2024 09:32 PM UTC

I am not sure how to make that work. In the example code above, I am already doing this as I use it to color the columns.

CellStyle = new Style(typeof(DataGridCell))

    {

        Setters =

        {

            new Setter

            {

                Property = DataGridCell.BackgroundProperty,

                Value = new SolidColorBrush(ColorRow(Columns.Count))

            }

        }

Can I use 2 setters with the same property of  DataGridCell.BackgroundProperty?

I need to be able to color my columns, this is always done, then change a row so all columns are one color when needed.



NY Nirmalkumar Yuvaraj Syncfusion Team April 17, 2024 03:15 PM UTC

Hi Phunction,


Based on the information provided, it seems that you're already configuring the cell style for columns. You've also inquired about setting the row background conditionally, for which we've proposed a method that involves utilizing the cell style once more. So, your question essentially pertains to whether it's possible to define the background property twice within the cell style.


To fulfill your requirement, you can directly assign the background color of the datagrid to the color previously set in the cell style. Subsequently, you can employ our approach to establish the conditional row background color within the cell style property. We have attached a sample and code snippet for your reference.


Code snippet:

<ContentPage.Resources>

    <Style TargetType="dataGrid:SfDataGrid" x:Key="datagridStyle">

        <Setter Property="Background" Value="red" />

    </Style>

</ContentPage.Resources>

 

<dataGrid:SfDataGrid x:Name="dataGrid2" Style="{StaticResource datagridStyle}" WidthRequest="600"

                     AutoGenerateColumnsMode="None"

                     ItemsSource="{Binding OrderInfoCollection}">

</dataGrid:SfDataGrid>

 


Regards,

Nirmalkumar


Attachment: SfDataGridSample_a91a79da.zip


PH Phunction April 17, 2024 04:07 PM UTC

That won't work for me, I already set the datagrid background color to what I need.

Also I have multiple different column colors.

It may be easier to restate what I want to do.

I have a grid say 20 columns, the first 5 are blue, the next 5 green, then red then yellow.

We will say column 20 contains the trigger value.

There are 10 rows.

Depending on what the userenters in column 20, if they enter Yes, than that entire row will color in orange, if the enter No, then it will revert back to the original column colors.

No columns are defined in the .xaml, just the grid.

I add all columns programmatically, as you see above. How can I do this?




NY Nirmalkumar Yuvaraj Syncfusion Team April 18, 2024 03:43 PM UTC

Hi Phunction,


We have endeavored to craft a sample that meets your specifications. Our efforts have focused on establishing cell styles based on column index and cell value. Upon thorough analysis, we have reached the conclusion that this can only be accomplished during the initial loading phase; it is not feasible to achieve it at runtime.



Regards,

Nirmalkumar




PH Phunction April 18, 2024 09:44 PM UTC

I could do it if I can get a column and row number from the converter, is that possible?

public class ColorConverter : IValueConverter


Does the grid class itself keep track of the last cell that was edited? I should be able to get the row/col from that. I could wire something up and keep track myself on current cell begin edit or end edit if that will work.

I would need to set the initial columns colors on load, then handle the colors on the converter.


Ideally if I could get the row and col each time the converter is called, that would work.





SM Sudarsan Muthuselvan Syncfusion Team April 19, 2024 11:30 AM UTC

Hi Phunction,


Query

Response

I could do it if I can get a column and row number from the converter, is that possible?

public class ColorConverter : IValueConverter

 

var setterBackground = new Setter

{

    Property = DataGridCell.BackgroundProperty,

    Value = new Binding

    {

        Source = RelativeBindingSource.Self,

        Converter = new ColorConverter()

    }

};

 

public class ColorConverter : IValueConverter

{

    object IValueConverter.Convert(object? value, Type targetType, object? parameter, CultureInfo info)

    {

        var gridCell = (value as DataGridCell);

        var columnIndex = gridCell.ColumnIndex;

        var rowData = gridCell.DataColumn.RowData;

        var cellValue = gridCell.CellValue;

        if ((rowData as OrderInfo)!.Status)

        {

            return Colors.Pink;

        }

        else

        {

            if (columnIndex >= 0 && columnIndex <= 2)

                return Colors.Blue;

            else if (columnIndex >= 3 && columnIndex <= 4)

                return Colors.Red;

            else if (columnIndex >= 5 && columnIndex <= 6)

                return Colors.Green;

        }

 

 

 

        return BindableProperty.UnsetValue;

    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)

    {

        throw new NotImplementedException();

    }

}

Does the grid class itself keep track of the last cell that was edited? I should be able to get the row/col from that. I could wire something up and keep track myself on current cell begin edit or end edit if that will work.

 We don't have an internal property to handle the last row column index. You would need to retrieve it manually from the CurrentCellEndEdit event.


We have attached a sample for your reference. Please refer to the following sample for more information. If you have any further concerns, please feel free to reach out.


Attachment: SfDataGridSample_f1b61068.zip

Marked as answer
Loader.
Up arrow icon