我有以下ResourceDictonary定義ResourceDictionary中只有一次
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:SharedHelpers="clr-namespace:Shared.Helpers;assembly=Shared"
xmlns:SharedViewModels ="clr-namespace:Shared.ViewModels;assembly=Shared"
xmlns:SharedViews="clr-namespace:Shared.Views;assembly=Shared"
>
<DataTemplate DataType="{x:Type SharedViewModels:DatabaseViewModel}">
<SharedViews:DatabaseView/>
</DataTemplate>
<DataTemplate DataType="{x:Type SharedViewModels:ProxyViewModel}">
<SharedViews:ProxiesView/>
</DataTemplate>
<DataTemplate DataType="{x:Type SharedViewModels:AppUserViewModel}">
<SharedViews:AppUserView/>
</DataTemplate>
<!--ViewModels-->
<SharedViewModels:DatabaseViewModel x:Key="DatabaseViewModel"/>
<SharedViewModels:AppUserViewModel x:Key="AppUserViewModel"/>
<SharedViewModels:ProxyViewModel x:Key="ProxyViewModel"/>
</ResourceDictionary>
,你可以看到這些資源是靜態的,我想從我的其他類和庫訪問它們 所以我所做的是在我的應用程序。 XAML我沒有定義詞典,如下
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="dict" Source="ResourceDict.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
從我後面的代碼我需要訪問這個字典的情況下,不必重新定義它,所以我發現
var databaseViewModelInstance = Application.Current.Resources.MergedDictionaries["dict"]["DatabaseViewModel"] as Shared.ViewModels.DatabaseViewModel;
但問題是它允許我只通過索引訪問字典,而不是通過它的名稱,我如何通過名稱訪問字典,而不必在每個類中定義新的資源字典實例想要訪問它?
以下工作就好
var databaseViewModelInstance = Application.Current.Resources.MergedDictionaries[0]["DatabaseViewModel"] as Shared.ViewModels.DatabaseViewModel;