[英]WPF Using images in generic.xaml template
我正在为直接从Control派生的自定义控件编写样式。 Visual Studio在Themes \\ generic.xaml文件中放置“自定义控件(WPF)”的样式。 我的样式包含一个我无法显示的图像,似乎关于如何在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>
我已经在根项目目录中的themes目录中添加了SmallHandle.png,也将其添加到了旧的“资源”页面中,尝试将构建操作更改为资源,嵌入资源,并尝试将图像手动复制到构建目录,但无效。 图像从不显示。
这必须与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指出的那样,我必须使用“完整”包URI表示法:
pack://application,,,/MyAssembly;components/SmallHandle.png
这对我来说很奇怪,因为该图像位于同一装配中。 不确定,看起来我是从dll外部引用的。
在Generic.xaml
访问图像没有什么异常,您只是没有正确引用它。 您可以使用以下格式在项目程序集中引用资源文件:
<Image Source="/AssemblyName;component/Subfolder/SmallHandle.png" />
如果图像直接位于项目根目录内( 不建议这样做),则可以按以下方式访问它们:
<Image Source="/AssemblyName;component/SmallHandle.png" />
如果图像位于另一个项目的文件夹中,则可以按以下方式访问它:
<Image Source="/ReferencedAssembly;component/Subfolder/SmallHandle.png" />
有关更多信息,请参见MSDN上的WPF中的Pack URI 。
更新>>>
在.NET 4中,上面的Image.Source
值将起作用。 但是,Microsoft在.NET 4.5中进行了一些可怕的更改,使许多不同的事情破裂,因此在.NET 4.5中,您需要使用完整的pack
路径,如下所示:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
如果您觉得仿冒了generic.xaml,可以从App.cs.xaml引用它,如下所示:
<App.Resources>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MY.NAMESPACE;component/Themes/generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</App.Resources>
您的generic.xaml文件应标记为“资源”。
另外,您的图像文件应标记为“资源”。
最后,像这样引用您的ImageSource:
<Image Source="Themes/IMAGE.png" />
或尝试
<Image Source="../Themes/IMAGE.png" />
就个人而言,我喜欢将样式模板放在它们自己的.xaml文件中,并将它们全部引用为MergedDictionaries。
Themes \\ Generic样式中的键入基本样式仅自动应用于“自定义控件”。
如果需要在用户控件中使用基于类型的样式,则需要在用户控件资源中添加generic.xaml。
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
还将Image Source URI更改为
<Image Source="pack://application:,,,/WpfCustomControlLibrary1;component/SmallHandle.png" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.