2014-05-10 21 views
0

我正在努力將值綁定到路徑ImageSource。當我嘗試設置新值時,我得到NullReferenceError。 我當前的代碼是:將圖像值綁定到wpf和c中的路徑#

在MainWindow.xaml路徑代碼以下

<Path x:Name="PPButton" Data="M110,97 L155,123 
     C135,150 135,203 153,227 
     L112,255 
     C80,205 80,150 110,97" 
     Stretch="none" MouseEnter="Path_MouseEnter_1" MouseLeave="Path_MouseLeave_1" > 
      <Path.Fill> 
       <ImageBrush ImageSource="{Binding ImageSource}"/> 
      </Path.Fill> 
    </Path> 

上MainWindow.xaml.cs在那裏我得到錯誤,我評論的背後Path_mouseEnter_1

Image image; 
private void Path_MouseEnter_1(object sender, MouseEventArgs e) 
     { 
      image.ImageSource = new Uri("/RoundUI;component/sadface.png", UriKind.Relative); // This "An unhandled exception of type 'System.NullReferenceException' occurred in RoundUI.exe" 
     } 

     private void Path_MouseLeave_1(object sender, MouseEventArgs e) 
     { 
      image.ImageSource = new Uri("/RoundUI;component/smileface.png", UriKind.Relative); 
     } 

類,其中約束值應該採取:

public class Image : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     private string title; 
     private Uri imageSource; 

     public Uri ImageSource 
     { 
      get 
      { 
       return imageSource; 
      } 
      set 
      { 
       imageSource = value; 
       if (PropertyChanged != null) 
       { 
        PropertyChanged(this, new PropertyChangedEventArgs("ImageSource")); 
       } 
      } 
     } 

     public void OnPropertyChanged(string name) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(name)); 
      } 
     } 
    } 

回答

1

在代碼後面的喲你必須使用完整的Pack URIs,包括前綴pack://application:,,,。而且你不應該指定UriKind.Relative

private void Path_MouseEnter_1(object sender, MouseEventArgs e) 
{ 
    image.ImageSource = new Uri("pack://application:,,,/RoundUI;component/sadface.png"); 
} 

編輯:看來你在這裏混淆了一些東西。現在它可能也許會更容易的圖像刷的ImageSource屬性綁定,而是直接在代碼中設置它的背後,如圖this answer你前面的問題:

<Path x:Name="PPButton" ... 
     MouseEnter="Path_MouseEnter_1" MouseLeave="Path_MouseLeave_1" > 
    <Path.Fill> 
     <ImageBrush/> 
    </Path.Fill> 
</Path> 

後面的代碼:

private void Path_MouseEnter_1(object sender, MouseEventArgs e) 
{ 
    var imageBrush = PPButton.Fill as ImageBrush; 
    image.ImageSource = new Uri("pack://application:,,,/RoundUI;component/sadface.png"); 
} 
+0

我是否需要替換此代碼中的某些內容,因爲我仍然收到NullReferenceError。 這是否有問題,如果我的「UI」中有我的RoundUI? – Taurib

+0

不知道,因爲你沒有說「UI」是什麼。在如上所述的Pack URI中,「RoundUI」是被引用程序集的名稱,「sadface.png」是該程序集的根文件夾中的映像文件,必須將其生成操作設置爲「Resource」。 – Clemens

+0

您究竟在哪裏得到NullReferenceException?僅僅因爲你沒有指定'image'字段? – Clemens