Search code examples
xamldatagridwinui-3

how to set selected row Foreground in uwp communitytoolkit datagrid Winui/UWP?


I want to change selected row Foreground in my Winui DataGrid , Seems there is no option to set it .


Solution

  • You can use the DataGrid's SelectionChanged event:

    private SolidColorBrush DataGridRowSelectedForegroundBrush { get; set; } = new(Colors.LightGreen);
    
    private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (sender is not DataGrid dataGrid)
        {
            return;
        }
    
        // DataGridRow has an "IsSelected" property but it's internal.
        // We can use Reflection to get this property.
        Type dataGridRowType = typeof(DataGridRow);
        PropertyInfo? isSelectedProperty = dataGridRowType.GetProperty("IsSelected", BindingFlags.Instance | BindingFlags.NonPublic);
    
        foreach (DataGridRow dataGridRow in dataGrid.FindDescendants().OfType<DataGridRow>())
        {
            if (isSelectedProperty?.GetValue(dataGridRow) is bool isSelected &&
                isSelected is true)
            {
                dataGridRow.Foreground = DataGridRowSelectedForegroundBrush;
                continue;
            }
    
            dataGridRow.Foreground = dataGrid.Foreground;
        }
    }
    

    BTW, I'm using the CommunityToolkit.WinUI.UI NuGet package to use FindDescendants().