2009-08-06 68 views
7

即時通訊嘗試重新創建一個非常簡單的C#項目示例我WPF,它的一個簡單的圖像查看器..從薩姆教自己C#,我設法讓打開的文件對話框打開,但怎麼做我將圖像路徑設置爲WPF中的image.source控件?WPF圖像控制源

private void SearchBtn_Click(object sender, RoutedEventArgs e) 
{ 
    Microsoft.Win32.OpenFileDialog openfile = new Microsoft.Win32.OpenFileDialog(); 
    openfile.DefaultExt = "*.jpg"; 
    openfile.Filter = "Image Files|*.jpg"; 
    Nullable<bool> result = openfile.ShowDialog(); 
    if (result == true) 
    { 
     //imagebox.Source = openfile.FileName; 
    } 
} 

回答

18
imagebox.Source = new BitmapImage(new Uri(openfile.FileName)); 
+0

謝謝你,你當如何設置Sizemode.zoom propertie的形象呢? – Dabiddo 2009-08-08 04:04:20

+0

也適合我!謝謝 – Azeem 2012-04-26 17:13:30

+0

謝謝。爲我工作 – 2018-01-15 04:47:47

3

,您需要更改文件名稱爲URI,然後創建一個BitmapImage的

if (File.Exists(openfile.FileName)) 
{ 
// Create image element to set as icon on the menu element 
BitmapImage bmImage = new BitmapImage(); 
bmImage.BeginInit(); 
bmImage.UriSource = new Uri(openfile.FileName, UriKind.Absolute); 
bmImage.EndInit(); 
// imagebox.Source = bmImage; 
} 
2

您還可以添加圖片作爲一種資源,即添加現有項目並將圖像的構建操作屬性更改爲資源

然後以此方式引用它

BitmapImage bitImg = new BitmapImage(); 
bitImg.BeginInit(); 
bitImg.UriSource = new Uri("./Resource/Images/Bar1.png", UriKind.Relative); 
bitImg.EndInit(); 

((Image)sender).Source = bitImg; 

這樣,你不需要包括與程序,它捆綁到包作爲一個資源