[英]Cannot set image source in code behind
關於在后面的代碼中設置圖像源有很多問題和答案,例如在代碼中設置WPF圖像源。
我已經遵循了所有這些步驟,但卻無法設置圖像。 我在VS2010中使用WPF C#進行編碼。 我將所有圖像文件放在名為“ Images ”的文件夾下,所有圖像文件都設置為Copy always 。 按照文檔中的說明,“ 構建操作”設置為“ 資源” 。
我的代碼如下。 我在XAML中設置了一個dog.png並將其更改為后面的代碼中的cat.png 。
// my XAML
<Image x:Name="imgAnimal" Source="Images/dog.png" />
// my C#
BitmapImage img = new BitmapImage();
img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png");
imgAnimal.Source = img;
然后我得到一張空虛的空白圖像。 我不明白為什么.NET會讓圖像設置如此復雜......
[編輯]
以下是有效的
imgAnimal.Source = new BitmapImage(new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png"));
它有效,但我看不出這兩個代碼有什么區別。 為什么早期不起作用而后者呢? 對我來說他們是一樣的..
試試以下:
imgAnimal.Source = new BitmapImage(new Uri("/FooApplication;component/Images/cat.png", UriKind.Relative));
默認UriKind是絕對的 ,你應該使用相對的 。
[編輯]
使用BeginInit和EndInit :
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(@"pack://application:,,,/FooApplication;component/Images/cat.png");
img.EndInit();
imgAnimal.Source = img;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.