【问题标题】:How to bind Image Source when the image is a file? [duplicate]图片为文件时如何绑定Image Source? [复制]
【发布时间】:2017-11-09 09:35:39
【问题描述】:

我有一个这样定义的硬编码图像源(图像位于文件中):

<Image Source="C:\Work\my_image.png"/>

图像已显示,一切正常。但现在我想绑定这个图像源。我试过这样:

<Image Source="{Binding ImageFilename}"/>

public class DataStuff
{
    public string ImageFilename { get; set; }

    public DataStuff(string imageFilename)
    {
        ImageFilename = imageFilename;
    }
}

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new DataStuff(@"C:\Work\my_image.png");
    }

但是图片没有显示出来。

我错过了什么?

【问题讨论】:

    标签: c# wpf windows visual-studio xaml


    【解决方案1】:

    解决了:-)

    public class DataStuff
    {
        public ImageSource ImageFilename { get; set; }
    
        public DataStuff(string imageFilename)
        {
            ImageFilename = new BitmapImage(new Uri(imageFilename, UriKind.Absolute));
        }
    }
    

    【讨论】:

    • 由于内置类型转换,它也应该与文件名字符串一起使用。但是,您可能需要在调用 InitializeComponent 之前分配 DataContext,或者在 ImageFilename 更改时触发属性更改通知事件。
    猜你喜欢
    • 2015-11-04
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2019-11-13
    • 2015-07-29
    • 2012-04-24
    相关资源
    最近更新 更多