2009-10-13 5 views
0

하나의 하위 즉 이미지가있는 사용자 정의 컨트롤이 있습니다. 사용자 정의 컨트롤의 기본 생성자에서 이미지 리소스를 표시하는 코드를 사용하여 기본 이미지를 설정하려고하지만 블렌드 미리보기 또는 실제로 실행중인 응용 프로그램에서 사용할 때 성공하지 못했습니다. 어떤 오류도 발생하지 않습니다. 이것이 가능하지 않아야합니까? 코드 숨김 여기UserControl에서 기본 이미지 만들기

<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> 

됩니다 : 여기

<MyNS:TestIcon 
    x:Name="m_TestIcon" 
/> 

은 사용자 컨트롤의 XAML 수 있습니다 : 여기

는 XAML 사용이다

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

에 한번 당신의 UserControl을에 형 BitmapImage의 DependencyProperty를 추가하고 여기에 이미지 컨트롤을 바인딩합니다. DP를 등록함으로써 기본값을 지정하십시오.