【问题标题】:Global styles from App.xaml applying in designer but not at runtime as of recently来自 App.xaml 的全局样式在设计器中应用,但最近在运行时不应用
【发布时间】:2016-03-03 17:02:59
【问题描述】:

问题

我正在开发一个应用程序,最近我在添加更多部分时重新组织了文件结构。大约在这个时候,我注意到在运行时,我的 App.xaml 中的样式没有得到应用。我在构建之前一次做了很多代码更改,所以我不确定可能发生了什么变化。

信息

App.xaml 在停止应用之前保持不变。

我的程序布局为有一个主 <ContentControl>,我将一些视图绑定到一些 MVVM 操作。最初,我将程序的不同子功能的所有视图放在一个 Views 文件夹中,但个别部分变得太大,因此我将它们从这里拆分出来:

<Project>/Models
<Project>/ViewModels
<Project>/Views

<Project>/EventEditor/Models
<Project>/EventEditor/ViewModels
<Project>/EventEditor/Views
<Project>/ConfigurationEditor/Models
<Project>/ConfigurationEditor/ViewModels
<Project>/ConfigurationEditor/Views

我的 UserControl 没有自己的任何资源或样式,目前只能使用 App.xaml 中的资源或样式。

我只有 1 个 App.xaml 文件,并且在单个视图 XAML 之外没有包含样式/字典/等的其他文件。

这是我的 App.xaml:

<Application x:Class="EventSuite.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:EventSuite"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <!-- Global Styles -->
    <Style TargetType="ListBoxItem">
        <Setter Property="FontSize" Value="14" />
    </Style>
    <Style TargetType="TextBlock">
        <Setter Property="FontSize" Value="14" />
    </Style>
    <Style TargetType="Label">
        <Setter Property="FontSize" Value="14" />
    </Style>
    <Style TargetType="Button">
        <Setter Property="Margin" Value="2,0,2,0"/>
        <Setter Property="Padding" Value="2"/>
        <Setter Property="FontSize" Value="14"/>
    </Style>
</Application.Resources>

采取的步骤

  1. 干净的构建/重建
  2. 打破并使用 Tree Visualizer 进行调查(没有运气)
  3. 不同的文件/项目。我发现的任何东西都不会导致这种情况(我不知道要寻找什么)

问题

  1. 有没有办法调试正在使用的样式?我尝试了 WPF Tree Visualizer,它在我的按钮上显示了 null 样式,这是我所期望的,因为我没有明确设置任何样式。
  2. 文件结构可以发挥作用吗?也许 App.xaml 没有被正确读取,或者它没有被正确应用。我没有看到任何警告或失败迹象。
  3. 命名空间相关?我希望不会...

总之,我对为什么 App.xaml 应用于设计时而不是运行时感到有些迷茫。为什么在对我的项目进行一些更改后会发生这种情况。我搞不清楚了!如果您需要更多信息或示例,请告诉我。

【问题讨论】:

    标签: c# wpf app.xaml


    【解决方案1】:

    原来这是 App.xaml StartupURI 的问题。

    我的 StartupURI 是 MainWindow.xaml,我的 App.xaml.cs 如下:

    public partial class App : Application
    {
        public App()
        {
            var dialog = new SageCenter.View.MainWindow();
            dialog.ShowDialog();
        }
    }
    

    它从未在我的应用程序上调用InitializeComponent(),但我的窗口仍在创建中。我将 StartupURI 保留在我的 App.xaml 中,并将 App.xaml.cs 更改为此来修复它:

        public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
        }
    }
    

    StartupURI="MainWindow.xaml" 导致 InitializeComponent() 调用实例化我的窗口。

    【讨论】:

    • 这个回答为我节省了几个小时。谢谢你。我们已经为 w/services 的依赖注入设置了 WPF,并且 App ctor 中的代码不再具有 InitializeComponent()。在 ctor 底部添加它解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多