我有一个用户控件,它有一个子控件-一个图像。我尝试使用用户控件的默认构造函数中的代码设置默认图像以显示图像资源,但到目前为止,无论是混合预览还是在运行的应用程序中实际使用它,都没有成功。我也没有任何错误。难道这不可能吗?
以下是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)
{
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(resource_name, UriKind.Relative);
myBitmapImage.DecodePixelWidth = icon_width;
myBitmapImage.EndInit();
return myBitmapImage;
}
}
解决方案
答案出现在
三Q
在下面。我把构造器的最后一行改成了下面的一行,结果成功了:
m_ViewIconUC_Image.Source = new BitmapImage(new Uri(@"/MyAssembly;component/Resources/Images/TestIcon32.png", UriKind.Relative));