Skip to main content
 首页 » 编程设计

c#之在 XAML 中使用单例之可能吗

2024年02月13日13EasonJim

我有一个名为 NotificationScheduler 的单例类。我的应用程序中真的可能只有其中一个。单例模式是通过“实例”属性实现的,并且只能通过该属性访问实例,如下所示:

    private static NotificationScheduler _instance = null; 
    public static NotificationScheduler Instance 
    { 
        get { return _instance ?? (_instance = new NotificationScheduler()); } 
    } 
 
    public NotificationScheduler() 
    { 
#if DEBUG 
        if (_instance != null) 
            Debug.WriteLine( 
                "WARN: A second Instance of NotificationScheduler has been created"); 
#endif 
        _instance = this; 
        init(); 
    } 

但我也有理由必须像这样在 XAML 中创建它:

        <NotifyIcon:NotificationScheduler x:Key="NotificationScheudlerInstance" 
                        IconSource="/Images\Icons/myicon.ico" 

我知道这不使用 Instance 属性!这可能吗?如果我像这样在代码中访问实例,当然会创建一个实例两次:

NotificationScheduler.Instance.DoSomething(); 
NotificationScheduler n = (NotificationScheduler) FindResource("NotifyIcon"); 
n.DoSomething(); 

目前,我的解决方案是执行 FindResource 操作以通过 XAML 代码创建实例,然后一切正常。

问题:我可以通过访问静态属性在 XAML 中创建资源吗?

请您参考如下方法:

为什么不像您的第一个代码段那样只拥有一个单例属性,并在 XAML 中使用 {x:Static NotifyIcon:NotificationScheduler.Instance} 引用它?如果它是单例,则它不需要是作用域资源。