C# 动态替换wpf图像源
我在xaml中使用的图像如下所示C# 动态替换wpf图像源,c#,wpf,C#,Wpf,我在xaml中使用的图像如下所示 <Image x:Name="JustMyImage" Width="635" Height="120" Canvas.Left="-19" Canvas.Top="-19" Source="../images/UnCategorized/Anywhere.png"/> 是否有一种直接的“一行”方法来替换图像。您可以这样做: JustMyImage.Source = new BitmapImage(new Uri(".\images\panel.
<Image x:Name="JustMyImage" Width="635" Height="120" Canvas.Left="-19" Canvas.Top="-19" Source="../images/UnCategorized/Anywhere.png"/>
是否有一种直接的“一行”方法来替换图像。您可以这样做:
JustMyImage.Source = new BitmapImage(new Uri(".\images\panel.PNG"))
您可以在资源中创建BitmapImage标记并引用它(我认为StaticResource可以工作,否则使用DynamicSource)
从“JustMyImage”中引用此位图图像。更新BitmapImage的URI时,“JustMyImage”应反映此更改。我使用转换器解决此问题:
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();
}
它将完全像那样工作,没有BeginInit和EndInit。否则,带有Uri参数的构造函数就没有任何意义了。@Vale:如果使用BitmapImage的参数化构造函数,它会起作用……有关详细信息,请参见此处“是”,理论上是。但是没有init我就无法让它工作part@Vale你可以在这里问一个问题,试着在这个问题上寻求帮助。
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();
}