在UserControl中创建默认图像

时间:2009-10-13 14:41:58

标签: wpf image user-controls constructor default

我有一个有一个孩子的用户控件 - 一个图像。我正在尝试使用User Control的默认构造函数中的代码设置默认图像以显示图像资源,但到目前为止,在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));

1 个答案:

答案 0 :(得分:1)

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