仅定义一次ResourceDictionary

时间:2013-12-15 21:40:59

标签: c# .net wpf xaml resourcedictionary

我有以下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>

你可以看到这些资源是静态的,我想从我的其他库和类访问它们 所以我所做的是在我的App.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;

2 个答案:

答案 0 :(得分:2)

按名称访问资源字典有点问题,因为它不是从FrameworkElement派生的,因此没有Name属性。如果有,您可以执行以下操作:

Application.Current.Resources.MergedDictionaries
                             .First(x => x.Name == "dict")["DatabaseViewModel"] as Shared.ViewModels.DatabaseViewModel;

但是,您可以按来源过滤:

,而不是按名称过滤
Application.Current.Resources.MergedDictionaries
                             .First(x => x.Source.OriginalString == "ResourceDict.xaml")["DatabaseViewModel"] as Shared.ViewModels.DatabaseViewModel;

答案 1 :(得分:1)

我不确定您是否可以按名称从MergedDictionaries集合中获取ResourceDictionary。但是,看起来您只想访问它以获取其中的特定资源(有意义)。

在这种情况下,您可能需要考虑使用FrameworkElement.TryFindResource

这应该搜索逻辑树并最终​​到达您的App.xaml级别。为清楚起见,您应该可以通过

获取 DatabaseViewModel
FrameworkElement fe = new FrameworkElement();
var myResource = fe.TryFindResource("DatabaseViewModel");