0

我有一个有一个孩子的用户控件 - 一个图像。我正在尝试使用用户控件的默认构造函数中的代码设置默认图像以显示图像资源,但到目前为止,无论是混合预览还是当我在正在运行的应用程序中实际使用它时都没有成功。我也没有收到任何错误。这不应该是可能的吗?

这是 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));
4

1 回答 1

1

尝试将 BitmapImage 类型的 DependencyProperty 添加到您的 UserControl 并将图像控件绑定到它。通过注册 DP 指定其默认值。

于 2009-10-13T21:48:01.287 回答