2014-01-22 70 views
0

在c#中我正在使用xaml設計器來製作應用程序。xaml更改圖片源

問題:如果我改變所述圖像源到另一個圖像源,沒有出現:雖然,如果圖像已經定義,IT改變爲「NULL」(NO IMAGE)

我已經使用的方法(其我在網上找到)將圖像源(字符串)更改爲圖像(對象)。

我已經嘗試了多次改變一些xaml圖片的圖像源,只需將xaml中的圖像源更改爲另一圖像(我放入該項目中),但不幸的是,當我這樣做時圖像不可見。

的圖像和方法我用的是以下物質:

MS-APPX:///Assets/bank_employee.jpg」

imageFromXaml.Source = imgCreatedFromMethod.Source; 

private static Image srcToImage(string source) 
{ 
     Uri imageUri = new Uri(source);  
     BitmapImage imageBitmap = new BitmapImage(imageUri); 
     Image img = new Image(); 
     img.Source = imageBitmap;  
     return img; 
} 

請問你們誰知道這個問題可能是什麼?

回答

0

我也有類似的問題,而這個工作對我來說:

  var imageSource = new BitmapImage(); 
      imageSource.BeginInit(); 
      imageSource.StreamSource = memoryStream; 
      imageSource.CacheOption = BitmapCacheOption.OnLoad; 
      imageSource.EndInit(); 
+0

(您是否缺少using指令或程序集引用?) - 顯示此消息。你知道我應該添加哪個參考嗎? – Klyner

+0

如果您使用Windows窗體,它正在工作,但如果您使用Xaml它也可以工作? – Klyner

0

你試過結合蛋白g將XAML中的源代碼轉換爲URI,然後更新它?

像這樣:

<Image Source="{Binding ImageUri}" /> 

然後有一個屬性的地方在你的DataContext這將是這樣的:

public class myClass: INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private Uri imageUri; 

    public Uri ImageUri 
    { 
     get 
     { 
      return imageUri; 
     } 
     set 
     { 
      imageUri = value; 
      if(PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs("ImageUri")); 
      } 
     } 
    } 
} 
+0

我從來沒有試圖綁定一個XAML GUI的組件,但我認爲現在使用它可能會很好。謝謝,我會盡力在我的應用程序中實現這一點。 – Klyner

+0

@Klyner您應該仔細研究數據綁定,它是XAML最有用的功能之一。 – TylerD87

+0

感謝您的提示! 順便說一句:你必須做什麼讓下面的代碼工作? PropertyChanged(this,new PropertyChangedEventArgs(「ImageUri」)); c#找不到方法 – Klyner

0

您是否驗證了您的方法實際上成功並返回正確的圖像源?如果確實如此,則不應該重新分配Source。如果您將新創建的圖像本身加載到UI中,它是否保留其源代碼?

this.Content = imgCreatedFromMethod; // where "this" is the window 

順便說一句,它不需要實現自己的轉換功能。如果你有一個字符串,將是有效的XAML,你可以直接調用的XAML解析器使用來構建一個圖像源轉換器:

using System.Globalization; 
using System.Windows.Media; 

string stringValue = ... 

ImageSourceConverter converter = new ImageSourceConverter(); 
ImageSource imageSource = converter.ConvertFrom(
    null, CultureInfo.CurrentUICulture, stringValue); 

轉換器實例(在這種情況下ImageSourceConverter),也可以檢索動態地由System.ComponentModel.TypeDescriptor.GetConverter(typeof(TypeToConvertTo))

如果您使用數據綁定(如TylerD87's answer),此轉換也將自動完成。您還可以查看triggers並按照以下樣式定義兩個圖像:

<Image> 
    <Image.Style> 
     <Style TargetType="Image"> 
      <Setter Property="Source" Value="original path" /> 
      <Style.Triggers> 
       <Trigger ...> 
        <Setter Property="Source" Value="new path" /> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </Image.Style> 
</Image> 
+0

當我將第一行添加到我的代碼時,我的內容屏幕變黑。 – Klyner

+0

@Klyner是'imgCreatedFromMethod.Source' null? – nmclean

+0

如果我打印源代碼,它將返回Windows.UI.Xaml.Media.Imaging.BitmapImage ... – Klyner