动态替换wpf图像源

本文关键字:图像 wpf 替换 动态 | 更新日期: 2024-10-23 09:58:49

我在xaml中使用图像,如下所示,

<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;

是否有一种直接的"单行"方法来替换图像。

动态替换wpf图像源

您可以这样做:

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

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

从您的"JustMyImage"中引用此BitmapImage。当您更新BitmapImage的URI时,"JustMyImage"应该反映这一变化。

我使用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();
}