我有一个来自 DB 的图像路径,格式为:WPF 中的 Pictures/image_1.jpg 和 正在使用转换器。
我正在尝试在当前目录所在的位置创建一个 Uri; G:\Projects - Visual Studio\Stamps\Stamps\bin\debug
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(ImageSource))
{
if (value is string)
{
string str = value.ToString();
Uri uri = null;
if (str == "None")
{
uri = new Uri(str, UriKind.RelativeOrAbsolute);
return new BitmapImage(new Uri("Pictures/NoImage.jpg", UriKind.RelativeOrAbsolute));
}
else
{
// This one does not work because my path has spaces
uri = new Uri(str, UriKind.RelativeOrAbsolute);
// The following works because it has no spaces in path name
//uri = new Uri("Z:/Zipped/" + str);
BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.UriSource = uri;
bmi.EndInit();
return bmi;
}
}
else if (value is Uri)
{
Uri uri = (Uri)value;
return new BitmapImage(uri);
}
}
return value;
}
然后在我有的 xmal 文件中;
<Window.Resources>
<con:ImageToSourceConverter x:Key="ImageSourceConverter"/>
</Window.Resources>
<DataGrid Name="dgUsers" AutoGenerateColumns="False"
IsReadOnly="True"
CanUserSortColumns="False"
VerticalGridLinesBrush="Transparent"
ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Header="Scott #" Binding="{Binding [ScottNumber]}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Width="42" Margin="0 5px" Source="{Binding Path=[ImagePath], Converter={StaticResource ImageSourceConverter}}"></Image>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Description" Binding="{Binding [Description]}" />
</DataGrid.Columns>
</DataGrid>
找不到文件路径,路径中有空格时不显示图像,没有空格时它工作正常。 所以我现在的问题是在创建 Uri 时我是否处理路径中的空格?
我也尝试过创建绝对 Uri 并用“%20”和“+”替换空格,但都导致异常。
答案 0 :(得分:0)
This article solved my problem
var baseUri = Environment.CurrentDirectory;
uri = new Uri($"file:///{baseUri}" + "/" + str, UriKind.RelativeOrAbsolute);
通过将 file:/// 添加到 Uri,它成功解析!