1 つの子 (イメージ) を持つユーザー コントロールがあります。ユーザー コントロールの既定のコンストラクターでコードを使用して既定の画像を設定して画像リソースを表示しようとしていますが、これまでのところ、Blend プレビューでも実行中のアプリで実際に使用しても成功していません。エラーも発生しません。これは可能であるべきではありませんか?
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));