【问题标题】:Silverlight application resources for global access to a singleton用于全局访问单例的 Silverlight 应用程序资源
【发布时间】:2011-01-11 03:09:13
【问题描述】:

我有一个单例,一旦点击它就会加载用户配置文件信息,我想在我的 SL3 应用程序中使其成为应用程序级资源,以便整个应用程序的元素可以绑定到它。

我的实例化代码版本很简单

UserProfile x = UserProfile.GetInstance();

我希望能够在 app.xaml 文件中的 xaml 中执行此操作,而在 WPF 中我们有 ObjectDataProvider,因此我可以表达类似

的内容
<ObjectDataProvider MethodName="GetInstance" 
ObjectType="{x:Type local:UserProfile}" x:Key="CurrentUserProfile"/>

我正在努力在 SL3 中为此找到正确的实现。

【问题讨论】:

    标签: c# silverlight data-binding xaml singleton


    【解决方案1】:

    正如您指出的,Silverlight 没有ObjectDataProvider。如果您需要它提供的功能,例如延迟实例化,您需要构建自己的类来处理它。如果您实际上并不需要这些功能,那么只需在启动时将UserProfile 的实例添加到App.Resources:-

     private void Application_Startup(object sender, StartupEventArgs e)
     {
        Resources.Add("CurrentUserProfile", UserProfile.GetInstance());
        RootVisual = new MainPage();
     }
    

    【讨论】:

    • 我真的希望在纯 xaml 中实现这一点,但如果我没有很快从某人那里得到基于 xaml 的解决方案,那么我会给你打勾……谢谢。
    【解决方案2】:

    Silverlight has no ObjectDataProvider.

    也就是说,您可以使用 Silverlight 对象的 DataContext .....

    Application.DataContext = UserProfile.GetInstance();
    

    【讨论】:

    • 如果您需要将 UserControls 等上的 DataContext 分配给一些真实的应用程序数据而不是外围用户信息,会发生什么?
    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2011-07-25
    • 2015-07-17
    • 1970-01-01
    相关资源
    最近更新 更多