将字符串值赋给img source wpf

问题描述 投票:1回答:2
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
    // TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]

    if (Convert.ToInt32(navigationParameter) >= 0)
    {
        BindData();
        BindData();
        txt1.Text = data[Convert.ToInt32(navigationParameter)].Name;
        Img.Source = data[Convert.ToInt32(navigationParameter)].ImagePath;
    }

我想将img源设置为字符串。

wpf wcf-binding .net-4.5
2个回答
1
投票

你可以写

Img.Source = new BitmapImage(new Uri(data[Convert.ToInt32(navigationParameter)].ImagePath));

UPDATE

如果ImagePath是一个相对路径,你可以这样写:

var path = data[Convert.ToInt32(navigationParameter)].ImagePath;
var uri = new Uri(path, UriKind.Relative);
Img.Source = new BitmapImage(uri);

0
投票
myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");

public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
    var uri = new Uri(parent.BaseUri, path);
    BitmapImage result = new BitmapImage();
    result.UriSource = uri;
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.