Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何仅设置DataGrid中的按钮的样式?_C#_Wpf - Fatal编程技术网

C# 如何仅设置DataGrid中的按钮的样式?

C# 如何仅设置DataGrid中的按钮的样式?,c#,wpf,C#,Wpf,在App.xaml中,我已为所有按钮设置了样式 <Style TargetType="Button"> <Setter Property="Margin" Value="3"/> </Style> 我意识到如果按钮在数据网格中,那么我不需要空白。我有很多DataGrid,我把这些代码一个接一个地放到了所有的数据网格中 <DataGrid.Resources> <Styl

在App.xaml中,我已为所有按钮设置了样式

    <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"/>