我正在为直接从Control派生的自定义控件编写样式。Visual将“自定义控件(WPF)”的样式放在Themes\generic.xaml文件中。我的样式包含一个无法显示的图像,似乎在如何从generic.xaml文件中设置图像源方面有一些特殊之处。
我设法用一个更简单的场景重现了这个问题。创建一个"WPF自定义控件库“,然后在themes\generic.xaml中为类似这样的按钮添加样式。这是我完整的generic.xaml:
<ResourceDictionary
...
<Style TargetType="{x:Type Button}">
<Setter Property="Content">
<Setter.Value>
<Image Source="SmallHandle.png"></Image>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>在此之后,我创建了一个UserControl (在同一个项目中),其中只包含一个按钮(为了测试样式),如下所示:
<UserControl x:Class="BlendControls.UserControl1"
...
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Button/>
</UserControl>我在根项目目录中添加了SmallHandle.png,在themes目录中,我还将它添加到了good old Resources页面中,尝试将构建操作更改为资源,嵌入式资源,尝试手动将映像复制到构建目录,但没有效果。图像永远不会显示。
这必须与generic.xaml文件相关,因为将整个样式复制到放置Button的文件中很好。也就是说,下列工作如预期的那样:
<UserControl x:Class="BlendControls.UserControl1"
...
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Content">
<Setter.Value>
<Image Source="SmallHandle.png"></Image>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Button></Button>
</UserControl>那么,我应该如何设置来自generic.xaml的图像源呢?或者,我应该将自定义控件的样式/模板放在哪里?
-解决办法
正如Sheridan所指出的,我必须使用“完整”pack表示法:
pack://application,,,/MyAssembly;components/SmallHandle.png这在我看来很奇怪,因为图像在同一个程序集中。不确定,看起来我是从dll外部引用的。
发布于 2014-02-05 21:21:54
在Generic.xaml中访问图像没有什么不寻常的,只是没有正确地引用它。可以使用以下格式引用项目程序集中的资源文件:
<Image Source="/AssemblyName;component/Subfolder/SmallHandle.png" />如果您的图像直接位于项目根目录中(不建议这样做),那么您可以这样访问它们:
<Image Source="/AssemblyName;component/SmallHandle.png" />如果您的图像位于另一个项目的文件夹中,那么您可以这样访问它:
<Image Source="/ReferencedAssembly;component/Subfolder/SmallHandle.png" />有关更多信息,请参见MSDN上的在WPF中打包URI页面。
更新>>>
在.NET 4中,上述Image.Source值可以工作。但是,微软在.NET 4.5中做了一些可怕的更改,打破了许多不同的东西,因此在.NET 4.5中,您需要使用完整的pack路径,如下所示:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">发布于 2014-02-05 19:59:09
如果您不觉得您的generic.xaml正在被选中,您可以在App.cs.xaml中引用它,如下所示:
<App.Resources>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MY.NAMESPACE;component/Themes/generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</App.Resources>您的generic.xaml文件应该标记为"Resource“。
此外,您的图像文件应标记为“资源”。
最后,这样引用您的ImageSource:
<Image Source="Themes/IMAGE.png" />或者尝试
<Image Source="../Themes/IMAGE.png" />就我个人而言,我喜欢将我的样式模板放在它们自己的.xaml文件中,并将它们全部引用为MergedDictionaries。
发布于 2014-02-05 20:29:25
主题\泛型样式中的类型化基样式仅自动应用于自定义控件。
如果需要在用户控件中使用基于类型的样式,则需要将generic.xaml添加到用户控件资源中。
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>还将更改为
<Image Source="pack://application:,,,/WpfCustomControlLibrary1;component/SmallHandle.png" /> https://stackoverflow.com/questions/21586109
复制相似问题