将 WPF 本地资源转换为应用程序资源
本文关键字:资源 转换 应用程序 WPF | 更新日期: 2023-09-27 18:32:58
我在 XAML 中有一个本地资源,我希望它被代码的其他部分使用。如何使其"全局"(即应用程序范围的资源)?这是我的本地资源:
<ResourceDictionary >
<local:BoolToLightConvertor x:Key="LightConverter" / >
</ResourceDictionary>
我怎样才能把它放在应用程序.xaml中?
应用程序资源除了在元素或窗口级别定义资源外,您还可以定义特定应用程序中的所有对象均可访问的资源。您可以创建应用程序资源,通过打开 App.xaml 文件(适用于 C# 项目)或应用程序 .xaml 文件(对于 Visual Basic 项目)并将资源添加到 Application.Resources 集合中,如此处显示:
<Application x:Class="WpfApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<SolidColorBrush x:Key="appBrush" Color="LightConverter" />
</Application.Resources>
</Application>
创建一个文件(例如 SharedResources.xaml),如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Your.Namespace.Here;assembly=Your.Assembly.Here">
< local:BoolToLightConvertor x:Key="LightConverter" / >
</ResourceDictionary>
在 App.xaml 中添加以下行:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="SharedResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type Rectangle}" />
</ResourceDictionary>
</Application.Resources>
现在可以在 XAML 中使用此转换器
(<Style TargetType="{x:Type Rectangle}"/>
是阻止忽略资源字典的 WPF 错误的解决方法,SO 上的另一个问题建议这样做。不幸的是,该链接现在躲过了我)