我想使用 C# 在运行时更改图像源。我试过了。
在 MainPage.xaml 中,
<Image x:Name="myImage" HorizontalAlignment="Left"
Height="125"
Margin="86,76,0,0"
VerticalAlignment="Top"
Width="220" />
<Button Content="Button"
HorizontalAlignment="Left"
Margin="134,230,0,0"
VerticalAlignment="Top"
Click="Button_Click"/>
并在 MainPage.xaml.cs 中
private void Button_Click(object sender, RoutedEventArgs e)
{
myImage.Source = new BitmapImage(new Uri("/Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Relative));
}
它没有显示编译时错误,但是当我运行它并单击 Button 时,它显示了一个异常。它说“mscorlib.ni.dll 中出现类型为‘System.ArgumentException’的异常,但未在用户代码中处理。”
请您参考如下方法:
提示在异常中:
The given System.Uri cannot be converted into a Windows.Foundation.Uri
您需要为通用 XAML 应用使用绝对 URI:
myImage.Source = new BitmapImage(new Uri(
"ms-appx:///Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Absolute));
