[英]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.