[英]Change image source in code behind - Wpf
我需要動態設置圖像源,請注意我的圖像在網絡上的某個地方,這是我的代碼
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri(@"pack://application:,,,\\myserver\\folder1\\Customer Data\\sample.png");
logo.EndInit(); // Getting the exception here
ImageViewer1.Source = logo;
例外:
URI 前綴無法識別
以上解決方案都不適合我。 但這確實:
myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));
你只需要一行:
ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png"));
您在此處使用的包語法是針對在應用程序中作為資源包含的圖像,而不是針對文件系統中的松散文件。
您只需要將實際路徑傳遞給 UriSource:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
沒有一種方法對我有用,因為我需要從文件夾中提取圖像而不是將其添加到應用程序中。 以下代碼有效:
TestImage.Source = GetImage("/Content/Images/test.png")
private static BitmapImage GetImage(string imageUri)
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri, UriKind.RelativeOrAbsolute);
bitmapImage.EndInit();
return bitmapImage;
}
你們都錯了! 為什么? 因為您只需要此代碼即可工作:
(圖像視圖)/ C# Img 是:您的圖像框
保持原樣,不做更改(“ms-appx:///)這是代碼,而不是您的應用程序名稱圖像是您項目中的文件夾,您可以更改它。 dog.png 是您文件夾中的文件,以及我做我的文件夾'Images'和文件'dog.png'所以uri是:“ms-appx:///Images/dog.png”和我的代碼:
private void Button_Click(object sender, RoutedEventArgs e)
{
img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.