在运行中替换wpf图像源

时间:2012-08-06 04:52:33

标签: c# wpf

我正在使用xaml中的Image,如下所示,

<Image x:Name="JustMyImage" Width="635" Height="120" Canvas.Left="-19" Canvas.Top="-19" Source="../images/UnCategorized/Anywhere.png"/>

如果我想动态更改图像源,我需要执行以下代码

 BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri(".\images\panel.PNG", UriKind.Relative);
            bi.EndInit();

            this.JustMyImage.Source = bi;

是否有直接的“一行”方法来替换图像。

3 个答案:

答案 0 :(得分:0)

你可以这样做:

 JustMyImage.Source = new BitmapImage(new Uri(".\images\panel.PNG"))

答案 1 :(得分:0)

您可以在参考资料中创建一个BitmapImage标记并引用它(我认为StaticResource可以工作,否则使用DynamicResource)。

从“JustMyImage”引用此BitmapImage。当您更新BitmapImage的URI时,“JustMyImage”应该反映此更改。

答案 2 :(得分:0)

我使用Converter解决此问题:

public class KepPathKonverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        BitmapImage o;
        try
        {
            o = new BitmapImage(new Uri($"{Main.baseDir}\\{value}"));
        }
        catch (Exception ex)
        {
            o = new BitmapImage();
        }
        return o;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
相关问题