XAML中样式的奇怪行为

时间:2012-05-21 15:18:54

标签: wpf xaml

我无法理解为什么会这样。我在WPF中有一个简单的应用程序。这个应用程序有一个窗口,并且在App.xaml中定义了一种样式,它改变了所有按钮的样式:

<Application x:Class="PruebasDesk.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Window1.xaml">
    <Application.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Height" Value="23"></Setter>
            <Setter Property="Width" Value="75"></Setter>
            <Setter Property="Background" Value="DarkCyan"></Setter>
        </Style>
    </Application.Resources>
</Application>

这很好用,所有按钮都有样式。现在,这是问题所在。如果不是使用StartupUri属性来启动应用程序,而是使用OnStartup方法启动它:

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            Window1 win1 = new Window1();
            win1.Show();
        }
    }

应用程序的按钮不会应用App.xaml中定义的按钮样式。但是......如果我向App.xaml添加另一种样式,就像这样:

<Application x:Class="PruebasDesk.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             >
    <Application.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Height" Value="23"></Setter>
            <Setter Property="Width" Value="75"></Setter>
            <Setter Property="Background" Value="DarkCyan"></Setter>
        </Style>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Height" Value="23"></Setter>
            <Setter Property="Width" Value="180"></Setter>
            <Setter Property="Background" Value="Azure"></Setter>
        </Style>
    </Application.Resources>
</Application>

然后按钮获得应用的样式!这对我来说似乎很奇怪。有谁知道我错过了什么?

1 个答案:

答案 0 :(得分:0)

我无法肯定地告诉你为什么会出现这种行为,但我可以告诉你,最佳做法会让你远离以这种方式使用App.xaml。我认为更好的做法是仅在app.xaml中合并您的资源字典。存储实际样式是创建无法管理的项目的好方法。

创建一个新的ResourceDictionary文件并添加这些样式。在添加更多字典时合并字典。

  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Common.xaml"/>
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>

或者,您可以加入事件Startup(app.xaml:Startup="App_Startup"),而不是覆盖OnStartup。这将与您定义的App.xaml资源设置一起使用。这可能是一个时间问题。

相关问题