gpt4 book ai didi

c# - 为什么 "the resource could not be resolved"使用 ComponentResourceKey?

转载 作者:太空宇宙 更新时间:2023-11-03 13:26:50 32 4
gpt4 key购买 nike

我尝试使用 ComponentResourceKey 重用自定义资源,但它不起作用,我收到此警告:

警告 12 无法解析资源“{ComponentResourceKey ResourceId=SadTileBrush, TypeInTargetAssembly={x:Type res:CustomResources}}”。

这是 ResourceLibrary/Themes/generic.xaml:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ResourceLibrary">
<ImageBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:CustomResources},
ResourceId=MyBrush}"
ImageSource="ResourceLibrary;component/../../myImage.jpg">
</ImageBrush>
</ResourceDictionary>

ResourceLibrary/CustomResources.cs:

namespace ResourceLibrary{
public class CustomResources{}
}

用法如下(在SomeOtherProject/MyWindow.xaml中):

<Button Background="{DynamicResource {ComponentResourceKey
TypeInTargetAssembly={x:Type res:CustomResources},
ResourceId=MyBrush}}"> Some text </Button>

为什么“无法解析资源”?

请注意,我知道 SO 问题“Getting a ComponentResourceKey to Work?”,但这种情况下的问题出在代码隐藏中,无论如何我都缺少...

最佳答案

当您使用 ComponentResourceKey 时,请确保 xmlns 前缀与 .dll 类文件不同

((DLL = 'Local' - 这个类 = 'res')

<Button Background="{DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type res:CustomResources}, ResourceId=SadTileBrush}}" Padding="5" Margin="5" FontWeight="Bold" 
FontSize="14" Content="A Resource From ReusableResourceLibrary" />

我创建了这个字典类来嵌入/合并我的 .dll 字典

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

<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/ReusableResourceLibrary;component/Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
<ImageBrush x:Key="DicTileBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 50 50" ImageSource="../Resources/Images/Smiley_Happy.png" Opacity="0.3" />
</ResourceDictionary>

然后在我的实际窗口/用户控件中,我将窗口/用户控件资源与上面的资源字典合并,它起作用了

希望对你有帮助

关于c# - 为什么 "the resource could not be resolved"使用 ComponentResourceKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22127424/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com