在我的 WPF 中,我希望每次用户单击右键时屏幕上的图像都会发生变化。问题是我一直收到相同的错误消息:
'Invalid URI: The format of the URI could not be determined.'
这是代码:
string pic1 = @"C:/Users/Milk/Desktop/exercises/wpf_1/portraits/1.png";
string pic2 = @"C:/Users/Milk/Desktop/exercises/wpf_1/portraits/2.png";
private void buttonRight_Click(object sender, RoutedEventArgs e)
{
List<string> portraits = new List<string>();
portraits.Add(pic1);
portraits.Add(pic2);
string ShowPicture = portraits[counter % portraits.Count];
image.Source = new BitmapImage(new Uri(portraits.ToString()));
counter++;
}
当我尝试只使用一个字符串时,如下所示:
image.Source = new BitmapImage(new Uri(pic1));
它工作正常,但是一旦它在列表中,它就找不到文件路径 - 至少,这对我来说是这样的。
知道如何解决这个问题以及我在哪里犯了错误吗?
最佳答案
这是因为.ToString()
通常返回对象的命名空间(除非被覆盖),在本例中是List 的命名空间;您需要将实际列表值一个一个地传递到 Uri
构造函数中。
你需要做的是像这样传入实际路径:
string ShowPicture = portraits[counter % portraits.Count];
image.Source = new BitmapImage(new Uri(ShowPicture));
关于c# - 无法获取 Uri 的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46103189/