简体   繁体   中英

How To Apply DataGrid.Resources To All DataGrids

I have created a WPF project with multiple DataGrid controls. I want them to display selected rows in the normal style even when the DataGrid loses focus. The code below works, but I want an easy way to apply this to all the DataGrids in the project without manually inserting this code into every DataGrid in the project. Can this be done in the app.xaml file or some other central resource?

  <DataGrid Name="dgStores" AutoGenerateColumns="True" AutoGeneratedColumns="DataGrid_AutoGeneratedColumns" > <DataGrid.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="DodgerBlue"/> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="White"/> <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DodgerBlue"/> <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="White"/> </DataGrid.Resources> </DataGrid> 

Create a style that targets DataGrid and add your resources to the style's resources and place this above the DataGrids in the visual tree (eg App.xaml):

<Style TargetType="DataGrid">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="DodgerBlue"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="White"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="DodgerBlue"/>
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="White"/>
    </Style.Resources>
</Style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM