i have the following ResourceDictonary
<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>
as you can see those resource are static and i want to access them from my other libraries and classes so what i did is in my App.xaml i did define the dictionary as the following
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="dict" Source="ResourceDict.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
from my code behind i need to access the instances in this dictionary without having to redefine it, so i found
var databaseViewModelInstance = Application.Current.Resources.MergedDictionaries["dict"]["DatabaseViewModel"] as Shared.ViewModels.DatabaseViewModel;
but the problem is it allows me to access the dictionary only by index and not by its name, how can i access the dictionary by its name without having to define a new resource dictionary instance in every class that i want to access it from?
the following works just fine
var databaseViewModelInstance = Application.Current.Resources.MergedDictionaries[0]["DatabaseViewModel"] as Shared.ViewModels.DatabaseViewModel;
Accessing a resource dictionary by name is a bit problematic since it doesn't derive from
FrameworkElement
and thus doesn't have aName
property. If it had, you could do the following:However, instead of filtering by name, you can filter by source: