c# - 如何在 MVVM 中的 wpf 中设置来自资源的图像源

标签 c# wpf image mvvm

我想将图像源设置为来自资源的图像。我有这个完美运行的 xaml:

  <Image Source="/MyApplicationName;component/Resources/SplashScreen/InternetPlaceHolder.jpg" Height="577" Width="700" />

我想以一种在代码中加载图像的方式更改它。所以我写了这段代码:

   <Image Height="577" Width="700"  x:Name="Image"/>


    MyImage = new Image();
    BitmapImage logo = new BitmapImage();
    logo.BeginInit();
    logo.UriSource = new Uri("pack://application:,,,/MyApplicationName;component/Resources/SplashScreen/InternetPlaceHolder.jpg");
    logo.EndInit();
    MyImage.Source = logo;

但它不起作用。

我检查过, Logo 不是从资源图像初始化的。显然 uri 有问题。我已经使用我找到的文档对其进行了检查,它的格式似乎是正确的。

我的问题:URI 有什么问题?

最佳答案

首先,您必须将图像属性 Build Action 设置为 Resource。然后尝试以下代码:

ImagePath = string.Format("{0}/{1}/{2}",AppDomain.CurrentDomain.BaseDirectory,"Resources/SplashScreen","InternetPlaceHolder.jpg");

XAML:

<Image  Source="{Binding ImagePath}" Height="577" Width="700" />

关于c# - 如何在 MVVM 中的 wpf 中设置来自资源的图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726942/

相关文章:

c# - 从 XML 更新插入 SQL Server 表

c# - 无法将 DialogResult 隐式转换为 MessageBoxResult

html - 在响应式 div 框中将矢量图像居中?

html - 使用 CSS 在网页中心对齐照片(带标题)

python - 在 python 枕头中堆叠多个图像

c# - .NET 中的加密/解密

c# - 程序关闭时 "First-chance exceptions"

c# - 加快图像列表的加载

c# - 平滑滚动的垂直文本以获得进度

wpf - 使用 WPF 和 MVVM 处理异常