wpf - 如果只有一个,则无法检索 WPF 应用程序资源

标签 wpf

这是我的代码或 WFP 中的错误吗?使用 VisualStudio 2013,面向 .NET 4.5.1。

<Application x:Class="WPFDemo.MyApp"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:vm="clr-namespace:WPFDemo.ViewModels">

    <Application.Resources>
        <vm:TestClass x:Key="tc" />
    </Application.Resources>
</Application>

   public partial class MyApp : Application
   {  
      protected override void OnStartup(StartupEventArgs e)
      {
         base.OnStartup(e);
         var mainWindow = new MainWindow();
         mainWindow.Show();
      }
   }

   public partial class MainWindow
   {
      public MainWindow()
      {
         InitializeComponent();
         object o = Application.Current.Resources["tc"];
      }
   }

问题:o 为空。

如果我添加至少一个其他任何类型的资源:
<Application.Resources>
    <vm:TestClass x:Key="tc" />
    <vm:TestClass2 x:Key="tc2" />
</Application.Resources>

并且在任何地方都不做其他更改,o 作为 TestClass 的一个实例返回。

嗯?

最佳答案

Application.Resources 时,我发现很少提到错误StartupURI时不加载没有定义

  • WPF: Cannot find resource defined in the App.xaml file
  • Application.Resources Not Loaded if Doesn't Have StartupURI Property
  • Bug: Single Entry Ignored

  • 这个问题似乎有 3 种解决方法(4 种包括创建虚拟资源)

    定义字典 ​​
    <Application.Resources>  
        <ResourceDisctionary>
            <ResourceDictionary.MergedDictionaries/>
            <vm:TestClass x:Key="tc" />
        </ResourceDisctionary>
    </Application.Resources>
    

    但这似乎很奇怪,因为它需要空 ResourceDictionary.MergedDictionaries标签

    不要覆盖 OnStartup 方法 但使用 Startup事件代替
    <Application ... Startup="Application_Startup">
    

    并在代码中
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        var mainWindow = new MainWindow();
        mainWindow.Show();
    }
    

    给您的 Application一个名字
    <Application ... x:Name="myApplication">
    

    关于wpf - 如果只有一个,则无法检索 WPF 应用程序资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192837/

    相关文章:

    c# - 基于 ViewModel 属性的条件 ControlTemplate

    c# - MVVM 在单击时更改网格的背景颜色

    wpf - 使用 ObjectDataProvider

    WPF如何将混合交互触发器添加到样式资源

    c# - MeasureOverride 和 ArrangeOverride 在 Windows Server 2016 上的执行速度比 Windows 10 专业版慢 3 倍

    c# - 在通过箭头键导航时禁用 WPF 下拉组合的 onSelectedIndexchanged 事件

    c# - 如何在 WPF 的一个 XAML 文件中添加多个类文件

    wpf - 从固定文档中删除页面?

    wpf - 我可以在WPF中使用什么控件来模拟Word颜色选择器?

    c# - DataGridColumn 与动态生成的数据绑定(bind)