Ama*_*duh 13 wpf mvvm resourcedictionary
我有一个在多个视图中引用的类,但我希望它们之间只共享一个类的实例.我已经实现了我的课程:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以将Singleton.Instance作为资源添加到我的资源字典中?我想写点类似的东西
<Window.Resources>
<my:Singleton.Instance x:Key="MySingleton"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
而不是{x:static my:Singleton.Instance}每次我需要引用它时都要写.
Jf *_*lac 17
接受的答案是错误的,它在XAML中是完全可能的.
<!-- assuming the 'my' namespace contains your singleton -->
<Application.Resources>
<x:StaticExtension Member="my:Singleton.Instance" x:Key="MySingleton"/>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)
不幸的是,XAML无法实现.但是您可以从代码隐藏中将单例对象添加到资源中:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e) {
base.OnStartup(e);
Resources.Add("MySingleton", Singleton.Instance);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10542 次 |
| 最近记录: |