【问题标题】:How to set ImageSource in a codebehindfile如何在代码隐藏文件中设置 ImageSource
【发布时间】:2012-08-07 13:46:47
【问题描述】:

我在 UserControl 中有属性 ImageSource。如何将代码中的ImageSource 设置为资源目录中的图像?

我想将图像源绑定到属性ImageSource。

<Image Source="{Binding Path=ImageSource}" />

【问题讨论】:

  • @Clemens 对不起,这是一个错字,我的意思是ImageSource

标签: wpf image code-behind imagesource


【解决方案1】:

为了从代码中的资源文件创建BitmapImage(派生自 ImageSource),您需要执行以下操作,前提是文件 MyImage.jpg 位于 Visual Studio 的名为 Images 的文件夹中项目,并且它的Build Action 设置为Resource:

var uri = new Uri("pack://application:,,,/Images/MyImage.jpg"); 
ImageSource = new BitmapImage(uri); // set the ImageSource property

另见this answer。


你也可以不绑定直接使用图片资源:

<Image Source="/Images/MyImage.jpg" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2021-06-07
    • 2012-06-05
    • 2012-09-05
    相关资源
    最近更新 更多