代码之家  ›  专栏  ›  技术社区  ›  Brian Stewart

在用户控件中创建默认图像

  •  0
  • Brian Stewart  · 技术社区  · 15 年前

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

    以下是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;
            }
        }
    

    解决方案

    答案出现在 三Q 在下面。我把构造器的最后一行改成了下面的一行,结果成功了:

    m_ViewIconUC_Image.Source = new BitmapImage(new Uri(@"/MyAssembly;component/Resources/Images/TestIcon32.png", UriKind.Relative));
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   Dmytro Laptin    15 年前