sourcetip

비활성 상태일 때 DataGrid가 선택한 행 색상

fileupload 2023. 4. 23. 11:04
반응형

비활성 상태일 때 DataGrid가 선택한 행 색상

DataGrid가 초점을 잃었을 때 선택한 행의 색상을 변경하려면 WPF DataGrid 스타일을 어떻게 해야 합니까?

오랜 시간 동안 검색한 결과, 이전에 게시된 Got/LostFocus 접근법보다 더 깔끔한 놀라울 정도로 간단한 방법을 발견했습니다.

<DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DarkGray"/>
</DataGrid.Resources>

이렇게 하면 비활성 배경색이 DarkGray로 설정되고 활성 배경색은 기본값으로 유지되지만 시스템 색상을 사용하여 변경할 수도 있습니다.물론 HighlightBrushKey도.

비활성 선택을 위한 포그라운드 리소스 키는 SystemColors입니다.비활성 선택HighlightTextBrushKey를 선택합니다.

4.0에서 동작하는 완전한 솔루션.이것은 CellStyle에서 확인할 수 있습니다.

<DataGrid.CellStyle>
    <!--Override Highlighting so that its easy to see what is selected even when the control is not focused-->
    <Style TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <Trigger  Property="IsSelected" Value="true">
                <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
                <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
            </Trigger>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="True" />
                    <Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=IsKeyboardFocusWithin}" Value="False" />
                </MultiDataTrigger.Conditions>
                <MultiDataTrigger.Setters>
                    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
                    <Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
                </MultiDataTrigger.Setters>
            </MultiDataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.CellStyle>

다음과 같이 합니다.

<DataGrid ...>
    <DataGrid.Resources> 
        <Style TargetType="DataGridRow"> 
            <Style.Resources> 
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red"/>                                  
            </Style.Resources> 
        </Style> 
   </DataGrid.Resources> 
...

이 대답들 중 어느 것도 내가 찾던 것을 주지 못했다.Steve Streeting이 평가한 상위 항목은 데이터 그리드의 다른 부분을 변경하고 싶지 않은 부분을 변경했으며, 다른 답변은 비활성 색상 변화를 제공하지 않고 행만 적절하게 대상으로 했습니다.다음은 비활성 색상을 변경하는 답변의 혼합입니다. 에만 해당되며 그리드의 다른 부분에는 해당되지 않습니다.

<DataGrid.Resources>
    <Style TargetType="DataGridRow">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DarkGray"/>
        </Style.Resources>
    </Style>
</DataGrid.Resources>

답변이 늦다:

이것은 에서 동작합니다.Net 4.0을 사용하면 색상을 하드코드할 필요가 없습니다.

<Style TargetType="DataGridRow">
    <Style.Resources>
         <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static SystemColors.HighlightColor}" />
         <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="{x:Static SystemColors.HighlightTextColor}"/>
    </Style.Resources>
</Style>

.Net Framework 4.0의 경우(또는 Inactive Selection을 사용하지 않는 경우)브러시 키):DataGridRow 스타일/컨트롤 템플릿을 만들고 다음 트리거를 추가합니다.

<ControlTemplate.Triggers>
    <Trigger  Property="IsSelected" Value="true">
        <Setter Property="Background" Value="{DynamicResource SelectionBrush}" />
    </Trigger>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="True" />
            <Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=IsKeyboardFocusWithin}" Value="False" />
        </MultiDataTrigger.Conditions>
        <MultiDataTrigger.Setters>
            <Setter Property="Background" Value="{DynamicResource InactiveSelectionBrush}" />
        </MultiDataTrigger.Setters>
    </MultiDataTrigger>
</ControlTemplate.Triggers>

프로그램의 모든 데이터 그리드에 적용되도록 ResourceDictionary에 추가했습니다.

<Style TargetType="DataGrid">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="LightGray"/>
    </Style.Resources>        
</Style>

"DataGrid" 섹션을 정의해야 합니다.CellStyle"은 다음과 같습니다.

    <DataGrid>
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="LightBlue"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.CellStyle>
    </DataGrid>

스스로 답을 찾아라.

DataGrid 리소스에 브러시를 추가하여 코드 뒤에서 '색상' 속성을 변경하고 HighlightBrushKey를 참조합니다.

<DataGrid.Resources>
    <SolidColorBrush x:Key="SelectionColorKey" Color="DarkGray"/>
    <Style TargetType="DataGridRow">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding Source={StaticResource SelectionColorKey}, Path=Color}"/>
        </Style.Resources>
    </Style>
</DataGrid.Resources>

그런 다음 DataGrids 이벤트 핸들러를 추가하여 색상을 수동으로 변경합니다.

private void DataGrid1_LostFocus(object sender, RoutedEventArgs e)
{
    ((SolidColorBrush)DataGrid1.Resources["SelectionColorKey"]).Color = Colors.DarkGray;
}

private void DataGrid1_GotFocus(object sender, RoutedEventArgs e)
{
    ((SolidColorBrush)DataGrid1.Resources["SelectionColorKey"]).Color = SystemColors.HighlightColor;
}

private void DataGrid1_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    ((SolidColorBrush)DataGrid1.Resources["SelectionColorKey"]).Color = Colors.DarkGray;
}

.net Framework 4.0의 경우

<Style TargetType="DataGridRow">
 <Style.Resources>
     <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="DarkGray" />
     <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="White"/>
 </Style.Resources>
</Style>

https://social.msdn.microsoft.com/Forums/vstudio/en-US/635642e6-4808-4b3e-8aea-c8c434397d0f/datagrid-lost-focus-brush?forum=wpf

.NET 4.0 이후의 경우:프로그래밍 방식으로 색상을 설정할 수도 있습니다.

if (TestDataGrid.RowStyle == null)
{
  TestDataGrid.RowStyle = new Style(typeof(DataGridRow));
}

// Set colors for the selected rows if focus is inactive
TestDataGrid.RowStyle.Resources.Add(SystemColors.ControlBrushKey, new SolidColorBrush(Colors.SkyBlue));
TestDataGrid.RowStyle.Resources.Add(SystemColors.ControlTextBrushKey, new SolidColorBrush(Colors.Black));

// Set colors for the selected rows if focus is active
TestDataGrid.RowStyle.Resources.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Colors.Red));
TestDataGrid.RowStyle.Resources.Add(SystemColors.HighlightTextBrushKey, new SolidColorBrush(Colors.White));

.NET 4.5 이상의 경우 색상을 프로그래밍 방식으로 설정하는 대신 다음과 같은 방법이 있습니다.

if (TestDataGrid.Resources == null)
{
  TestDataGrid.Resources = new ResourceDictionary();
}

// Set colors for the selected rows if focus is inactive
TestDataGrid.Resources.Add(SystemColors.InactiveSelectionHighlightBrushKey, new SolidColorBrush(Colors.SkyBlue));
TestDataGrid.Resources.Add(SystemColors.InactiveSelectionHighlightTextBrushKey, new SolidColorBrush(Colors.Black));

// Set colors for the selected rows if focus is active
TestDataGrid.Resources.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Colors.Red));
TestDataGrid.Resources.Add(SystemColors.HighlightTextBrushKey, new SolidColorBrush(Colors.White));

저도 비슷한 문제가 있었어요.시나리오에서는 RowBackground 및 AlternatingRowBackground에 색상이 할당된 DataGrid였습니다.DataGrid Lose Focus(데이터 그리드 포커스 손실)가 발생하면 선택한 행이 회색으로 바뀌어 DataGrid가 원하는 행을 클릭하여 포커스를 되찾으면 올바른 색으로 돌아갑니다.이 효과는 불쾌했다.먼저 Steve Streeting이 제안한 솔루션부터 설명하겠습니다.

<Style TargetType="DataGrid">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" 
                         Color="LightGray"/>
    </Style.Resources>
</Style>

단, 색상 = "투명"을 바꿉니다.

<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" 
                 Color="Transparent"/>

문제를 풀 수 있게 ..net 4.5아니다.net 4.0.

이 솔루션이 유용하기를 바랍니다.

잘못된 동작:

잘못된 행동

올바른 동작:

올바른 행동

언급URL : https://stackoverflow.com/questions/7998112/datagrids-selected-row-color-when-inactive

반응형