【问题标题】:UWP - C#: Save Uri into SQLite or how to convert string into Uri when I load a gridview?UWP - C#:将 Uri 保存到 SQLite 或加载网格视图时如何将字符串转换为 Uri?
【发布时间】:2018-02-25 13:21:59
【问题描述】:

我必须使用GridViewItem 样式的图像,每个GridViewItem 代表保存在 SQLite 数据库中的对象,当我将新对象保存到数据库中时,我必须从组合框中选择它使用的图像。

这是 Combobox 的定义:

<ComboBox x:Name="UriImage" Width="200" RelativePanel.Below="ActiveToggle">
      <ComboBoxItem Content="Element1" x:Name="element1" IsSelected="True"/>
      <ComboBoxItem Content="Element2" x:Name="element2"/>
      <ComboBoxItem Content="Element3" x:Name="element3"/>
</ComboBox>

然后我创建了它以将图像的相应 URI 与每个 ComboBoxItem 匹配

string ImageUriString=""; 

if (UriImage.SelectedValuePath == "Element1")
      ImageUriString = "ms-appx:///Assets/Orchid_2_FF.png";
else if (UriImage.SelectedValuePath == "Element2")
      ImageUriString = "ms-appx:///Assets/sapphire_orchid_FF.png";
else if (UriImage.SelectedValuePath == "Element3")
      ImageUriString = "ms-appx:///Assets/yellow-cowslip-orchid_FF.png";

Uri UriString = new Uri(ImageUriString, UriKind.RelativeOrAbsolute);

然后我将Uri字段添加到代表对象的类中 当我尝试保存新对象时出现此错误:Don't know how to read System.Uri

要在 Gridview 中加载对象,我使用这个:

private async void ReadAllSystemList_Loaded(object sender, RoutedEventArgs e)
{
   ReadAllSystemsList dbSystems = new ReadAllSystemsList();
   DB_FFSystems = await dbSystems.GetAllFFSystems(); //get all DB Systems       
   listBoxObj.ItemsSource = DB_FFSystems.OrderByDescending(i => i.ID).ToList();
}

和来自 Xaml 的数据绑定。

<Image Width="350" Height="200" x:Name="ElementImage" Source="{Binding ImageUri}">

我曾考虑将 URI 保存为字符串,但如何在加载 Gridview 时将字符串转换为 Uri?

【问题讨论】:

  • 您好 ZampTom,您可以使用转换器并仅绑定到字符串。但我认为绑定到 Imagesource 的字符串仍然有效?

标签: c# xaml uwp


【解决方案1】:

SQLite 无法存储和解析 URI,因此这是您遇到错误的根源。

您可以在数据库中安全地存储string 而不是Uri。通常理想的方法是有一个简单的类用作数据库模型(具有string 属性),然后在表示层中使用另一个类,它将具有Uri。通过这种方式,您可以获得良好的层分离,并且可以在不受数据库限制的表示层上拥有更实用的界面。您甚至可以使用 Automapper 之类的库轻松地从一种类型转换为另一种类型,而不必逐个属性地进行。

但是,如果您不想处理此问题,还有其他选择。首先 - 当绑定到 SourceImage 时,您根本不必从 string 转换为 Uri。 XAML 中内置了从 stringUri 的隐式类型转换,因此它应该可以按预期工作。

或者,您可以通过创建派生自IValueConverter 的类来实现转换器。这将覆盖Convert 方法并从传入的string 构建一个Uri 实例。然后您将转换器注册为具有x:Key 的资源并在代码中使用它:

Source="{Binding ImageUri, Converter={StaticResource StringToUriConverter}"

【讨论】:

    猜你喜欢
    • 2011-12-17
    • 2013-06-25
    • 2011-03-30
    • 2014-03-06
    • 2018-02-08
    • 2021-06-17
    • 1970-01-01
    • 2012-02-01
    • 2011-02-12
    相关资源
    最近更新 更多