c# - 无法获取 Uri 的文件路径

标签 c# wpf list uri

在我的 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/

相关文章:

c# - DataGridComboBoxColumn ActionHandler

c# - WPF 绑定(bind)未从 DispatcherTimer 更新

python - 通过循环追加 Python 字典列表

list - 实际使用Erlang中的不正确列表(可能是所有功能语言)

c# - 使用 ASP.NET MVC 从帮助程序调用 User.Identity.GetUserId()

c# - Linq - 使用谓词的查询运算符 'Where' 不支持重载

c# - Ria 服务和导航属性问题

c# - 将焦点集中到扩展器内的组件

.net - GalaSoft.MvvmLight.WP71 编译错误,需要为 RelayCommand 添加对 System.Windows 的引用

python - 查找列表中不常见的元素