0
我有一個用戶控件有一個孩子 - 一個圖像。我試圖使用用戶控件的默認構造函數中的代碼來設置默認圖像來顯示圖像資源,但到目前爲止,在Blend預覽或實際在正在運行的應用程序中實際使用它時都沒有成功。我也沒有得到任何錯誤。這不可能嗎?在UserControl中創建一個默認圖像
這裏是XAML用法:
<MyNS:TestIcon
x:Name="m_TestIcon"
/>
下面是用戶控制的XAML:
<UserControl
x:Class="MyNS.TestIcon"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="m_TestIcon"
Height="32" Width="32"
>
<UserControl.Resources>
<Style TargetType="Image">
<Setter Property="Width" Value="32" />
<Setter Property="Height" Value="32" />
</Style>
</UserControl.Resources>
<Image
x:Name="m_TestIcon_Image"
/>
</UserControl>
這裏是代碼隱藏:
public partial class TestIcon : UserControl
{
public TestIcon()
{
InitializeComponent();
m_TestIcon_Image.Source = createBitmapImageFromResource("/Resources/Images/TestIcon32.png", 32);
}
private static BitmapImage createBitmapImageFromResource(string resource_name, int icon_width)
{
// Create source
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(resource_name, UriKind.Relative);
// To save significant application memory, set the DecodePixelWidth or
// DecodePixelHeight of the BitmapImage value of the image source to the desired
// height or width of the rendered image. If you don't do this, the application will
// cache the image as though it were rendered as its normal size rather then just
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = icon_width;
myBitmapImage.EndInit();
return myBitmapImage;
}
}
解
答案在下面Tri Q貢獻的鏈接中給出。我改變了構造函數的最後一行到下一行和它的工作:
m_ViewIconUC_Image.Source = new BitmapImage(new Uri(@"/MyAssembly;component/Resources/Images/TestIcon32.png", UriKind.Relative));