在 XAML 中设置全局样式

use*_*338 1 c# wpf xaml

是否有某种方法可以在 xaml 的资源字典中设置全局样式而无需在受影响的元素中指定任何特殊设置?

例如,假设我有 resdictionary.xaml 文件

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

 </ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

然后我有正常的 window.xaml 文件:

<Window x:Class="App.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
    Title="MainWindow" Height="500" Width="800" MinWidth="500" MinHeight="350">
<Window.Resources>
    <ResourceDictionary Source="resdictionary.xaml" />
</Window.Resources>   

 <Button Content="Button 1"/>
 <Button Content="Button 2"/>
 <Button Content="Button 3"/>
 </Window>
Run Code Online (Sandbox Code Playgroud)

我希望所有按钮都具有黑白背景渐变和 Calibri 字体。有没有办法在 resdictionary.xaml 中指定它而不必更改 window.xaml 文件?

AMS*_*AMS 5

例如,您可以创建一个 styles.xaml 页面并在其中添加所有样式

<Style x:Key="SubmitButtonStyle" TargetType="Button">
    <Setter Property="Height">
        <Setter.Value>28px</Setter.Value>
    </Setter>
    <Setter Property="Width">
        <Setter.Value>90px</Setter.Value>
    </Setter>
    <Setter Property="BorderThickness">
        <Setter.Value>1</Setter.Value>
    </Setter>
    <Setter Property="BorderBrush">
        <Setter.Value>#000000</Setter.Value>
    </Setter>
    <Setter Property="Background">
        <Setter.Value>#0073c6</Setter.Value>
    </Setter>
    <Setter Property="FontFamily" >
        <Setter.Value>Segoe UI</Setter.Value>
    </Setter>
    <Setter Property="FontSize">
        <Setter.Value>12px</Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)

您可以使用以下代码在您的窗口中引用styles.xaml。

    <UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary  Source="../Resources/Styles.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

您可以在页面中按以下方式使用该样式

<Button Style="{StaticResource TelerikRadSubmitButtonStyle}"/>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。