2010-11-24 4 views
2

이미지가 동적으로 변경되는 문제가 있습니다.WPF를 사용하여 C#에서 동적으로 이미지 변경

일부 배경 정보 : 선택할 수있는 요소가 포함 된 목록 상자가 있습니다. 이 항목은 식품 카테고리입니다. 사용자가 음식 중 하나를 클릭하면 페이지의 다른 위치에있는 이미지를 변경하고 싶습니다.

내 XAML 파일에는 다음이 포함

<Image Name="bigImage" Stretch="Fill" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center"/> 

을 사용자가 "bigImage는"변경 것이라고 특정 식품 카테고리를 클릭 그래서 때 내 음식 클래스에서

FoodCollection foods = (FoodCollection)this.FindResource("FoodCategory"); 
      Food f = foods[foodListBox.SelectedIndex]; 
      Title_TextBlock.Text = f.Name; 
      bigImage = f.MainImage; 

을 내가 변수라는 이미지 m_mainImage이 :

public class Food 
    { 
     ... 

     Image m_mainImage = new Image(); 
     String m_mainImagePath = string.Empty; 

     ... 

     public string MainImagePath{ 
      get { return m_mainImagePath; } 
      set 
      { 
       m_mainImagePath = value; 
       m_mainImage.BeginInit(); 
       m_mainImage.Source = new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute)); 
       m_mainImage.EndInit(); 
       RaisePropertyChanged("MainImage"); 
       RaisePropertyChanged("MainImagePath"); 
      } 
     } 

     public Image MainImage 
     { 
      get { return m_mainImage; } 
     } 


     public event PropertyChangedEventHandler PropertyChanged; 
     protected void RaisePropertyChanged(string name) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(name)); 
     } 

    } 
} 

어딘가에서 이미지를 "해결"해야하지만 나는 uncl했습니다. 그게 의미하는 바에 귀에.

m_mainImage.BeginInit(); 
        m_mainImage.Source = new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute)); 
        m_mainImage.EndInit(); 

미안 WPF와 C# 새로운 여전히 이니 은 내가 그것을 할 것이라고 생각했다. 미리 감사드립니다.

답변

0

당신이 윈도우의 DataContext 설정 했습니까? 이 PropertyChanged없이

때문에, 초기화되지 않습니다 :

if (PropertyChanged != null) 
    PropertyChanged(this, new PropertyChangedEventArgs(name)); 

것이다 PropertyChanged 등의 화재는 항상 null하지 않습니다.

+0

오, 어떻게 DataContext를 설정합니까? –

+0

@Aero - 가장 간단한 방법은'this.DataContext = this; '를 사용하여 생성자의 최상위 수준에서 설정하는 것입니다. 그러나 좀 더 구체적으로 지정할 수 있습니다. – ChrisF

0

설정 일부 양방향 바인딩 :

시도 :

bigImage.SetBinding(Image.SourceProperty, new Binding(){ 
     Source = f, 
     Path = new PropertyPath("MainImage"), 
     Mode=BindingMode.TwoWay 
    }); 

또는 :

<Image Name="bigImage" 
     Stretch="Fill" 
     Grid.Row="0" 
     Grid.Column="0" 
     HorizontalAlignment="Center" 
     VerticalAlignment="Center" 
     Source="{Binding Path=MyBitmapImage, Mode=TwoWay}"/> 

public BitmapImage MyBitmapImage 
{ 
    get 
    { 
     return new BitmapImage(new Uri(m_mainImagePath, UriKind.RelativeOrAbsolute)); 
    } 
} 
+0

그것은 컴파일 않으며, 실행. 첫 번째 방법을 시도했지만 이미지가 보이지 않는 것 같습니다 : –

+0

'MainImage'의 값을'BitmapImage'로, getter를'return m_mainImage.Source'로 변경하십시오; – Gabe

0

이 도움이 될 것입니다 확실하지,하지만 MainImagePath에 대한 세터에서 m_mainImage.EndInit()에 대한 호출이 RaisePropertyChanged("MainImage")에 대한 호출 후에 발생하지 않습니다 ...

앤드류

관련 문제