2012-04-16 79 views
0

下面是一些用於實例化WPF應用程序的ResourceManager的啓動代碼。如果我想通過xaml使這個可用,我會把它放在資源字典中嗎?使用ObjectProvider?還有別的嗎?實例化WPF對象並使它們可用

是否有理由更喜歡WPF應用程序中的另一個對象實例化的方法?

乾杯,
Berryl

var asm = Assembly.Load("SampleApp.Common"); 
var resourceMan = new ResourceManager("SampleApp.Common.Resources.SupportedCultures", asm); 
DataContext = new MainWindowVm(resourceMan); 

回答

1

在我看來,靜態類是最好的解決方案,如果你不需要更換應用程序生命週期中詞典:

public static class SampleAppCommonResources 
{ 
    private static ResourceManager _Manager; 

    public static ResourceManager Manager 
    { 
     get 
     { 
      if (_Manager == null) 
      { 
       var asm = Assembly.Load("SampleApp.Common"); 
       _Manager = new ResourceManager("SampleApp.Common.Resources.SupportedCultures", asm); 
      } 

      return _Manager; 
     } 
    } 
} 

XAML用法:

<Menu Tag="{x:Static local:SampleAppCommonResources.Manager}"> 

如果存在多行,多線程環境下,_Manager應該使用Interlocked.CompareExchange進行分配。