如何将样式应用于所有按钮?

Jas*_*n94 1 c# xaml windows-phone-7

如何以及在何处创建一个样式,为所有按钮控件提供资源蓝色(黄色边框,蓝色背景)?

它也可以添加到texbox吗?

是否有一个集中的地方,因为我希望这种风格能够影响我的应用程序中不同页面中的按钮?

Hos*_*Rad 6

在这些情况下,您可以使用Styles:

  • 您将在类型的多个控件上应用相同的属性(或成员)
  • 您将要保存好的和所需的类型状态,并在以后使用它.

您可以Style在控件的资源中添加它,或者ResourceDictionaries像这样:

<Style TargetType="Button">
    <Setter Property="BorderBrush" Value="Yellow"/>
    <Setter Property="Background" Value="Blue"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

如果你定义x:key,那么你应该明确说出哪个按钮跟随你的风格(例如<Button Style="{StaticResource myButtonStyleKey}">),否则你的风格将自动应用于按钮.

编辑:ResourceDictionary(已命名myStyles.xaml)添加到项目中(在名为的文件夹中MyResource).这是代码:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button">
        <Setter Property="BorderBrush" Value="Yellow"/>
        <Setter Property="Background" Value="Blue"/>
    </Style>
</ResourceDictionary> 
Run Code Online (Sandbox Code Playgroud)

然后在你的App.xaml添加中:

<Application x:Class="WPFApp.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MyResource/myStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)