C# 如何仅设置DataGrid中的按钮的样式?
在App.xaml中,我已为所有按钮设置了样式C# 如何仅设置DataGrid中的按钮的样式?,c#,wpf,C#,Wpf,在App.xaml中,我已为所有按钮设置了样式 <Style TargetType="Button"> <Setter Property="Margin" Value="3"/> </Style> 我意识到如果按钮在数据网格中,那么我不需要空白。我有很多DataGrid,我把这些代码一个接一个地放到了所有的数据网格中 <DataGrid.Resources> <Styl
<Style TargetType="Button">
<Setter Property="Margin" Value="3"/>
</Style>
我意识到如果按钮在数据网格中,那么我不需要空白。我有很多DataGrid,我把这些代码一个接一个地放到了所有的数据网格中
<DataGrid.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="0"/>
</Style>
</DataGrid.Resources>
有更聪明的方法吗?您可以为DataGrid定义样式,并在其中向特定修改添加子控件样式
如果要将此样式添加到所有数据网格,则无需定义key
请在Windows或用户控件级别添加资源文件,以便它应用所有子控件,如下所示:
<Window.Resources>
<Style TargetType="DataGrid">
<Style.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="Red" />
<Setter Property="Margin" Value="0" />
</Style>
</Style.Resources>
</Style>
<Window.Resources>
或
使用Window.Resources或App.Resources中的键声明样式,如下所示
<Window.Resources>
<Style TargetType="Button" x:Key="dataGridButtonStyle">
<Setter Property="Margin" Value="3"/>
<Setter Property="Background" Value="Wheat"/>
</Style>
</Window.Resources>
然后使用StaticResource和键将样式应用于控件。在本例中,键名为dataGridButtonStyle
<Button Style="{StaticResource ResourceKey= dataGridButtonStyle}" Content="Hello"/>
<Window.Resources>
<Style TargetType="Button" x:Key="dataGridButtonStyle">
<Setter Property="Margin" Value="3"/>
<Setter Property="Background" Value="Wheat"/>
</Style>
</Window.Resources>
<Button Style="{StaticResource ResourceKey= dataGridButtonStyle}" Content="Hello"/>