XAML 如何在uwp communitytoolkit数据网格Winui/UWP中设置选定行前景?

6xfqseft  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(142)

我想在我的Winui数据网格中更改选定的行前景,似乎没有设置它的选项。

nlejzf6q

nlejzf6q1#

您可以使用DataGridSelectionChanged事件:

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;
    }
}

字符串
顺便说一句,我正在使用CommunityToolkit.WinUI.UINuGet包来使用FindDescendants()

相关问题