c# - 使用 x :Shared ="False" resources in external assembly in WPF 时出错

标签 c# .net wpf xaml resourcedictionary

在我们的项目中,我们有一个 ResourceDictionary 和一些如下所示的图标:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Canvas x:Key="Icon.Refresh"
            x:Shared="False"
            Width="32"
            Height="32"
            Clip="F1 M 0,0L 32,0L 32,32L 0,32L 0,0">
        <Path .../>
        <Path .../>
        <Path .../>
    </Canvas>
</ResourceDictionary>

x:Shared="False" 属性是必需的,否则当我在多个 View 中使用它时图标会消失。

现在我们想用相同的图标创建另一个项目,所以我们决定将它们放在一个库项目中,两个项目都引用它。

但是当我们尝试运行应用程序时,我们总是会收到错误:

Shared attribute in namespace "http://schemas.microsoft.com/winfx/2006/xaml" can be used only in compiled resource dictionaries."

但我们无法摆脱 x:Shared="False" 属性,因为据我所知,这是阻止图标消失的唯一方法。

那么我们可以做些什么,通过项目引用在多个项目中共享图标而不消失图标?

最佳答案

从这个错误判断,我们可以理解x:Shared 属性只能用于compiled ResourceDictionary。引自 MSDN x:Shared Attribute :

The ResourceDictionary that contains the items with x:Shared must be compiled. The ResourceDictionary cannot be within loose XAML or used for themes.

Compiled ResourceDictionaryBuild action 设置 Page 的,在本例中,它被转换在运行时转换为 BAML(二进制应用程序标记语言)。创建新的 ResourceDictionary 时通常默认设置此属性。

BAML 只是 XAML,具有 已被解析、标记化并转换为二进制形式,以提高处理 XAML 文件的性能。 Adam Nathan WPF 书中的引述:

BAML is not like Microsoft intermediate language (MSIL); it is a compressed declarative format that is faster to load and parse (and smaller in size) than plain XAML. BAML is basically an implementation detail of the XAML compilation process.

因此,始终建议在 ResourceDictionary 中检查此标志,因为如果它被设置为 Resource,内存中将存储非打包版本的 XAML,这稍后可能会影响整个 WPF 应用程序的性能。

关于c# - 使用 x :Shared ="False" resources in external assembly in WPF 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22066727/

相关文章:

.net - 反转 WPF 图像的颜色

c# - 由于 DelegateCommand,WPF 应用程序中的内存泄漏

C#最快的2组排序数字的交集

c# - 有什么办法可以将输入插入到连续运行的网络作业中吗?

c# - 如何只显示最近添加的4条数据库记录?

c# - 将文件名(字符串参数)从子窗口传递到父窗口的非静态方法

c# - WPF:使用数据触发器/ bool 值重新启动 Storyboard?

wpf - System.Windows.Clipboard 和 System.Windows.Forms.Clipboard 之间有区别吗?

c# - 获取文化特定日期的日和月部分

c# - 以编程方式在登录项中的 MacOS 上注册 .Net Core 控制台应用程序