我必须使用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?
答案 0 :(得分:0)
SQLite无法存储和解析URI,因此这是您获得的错误的来源。
您可以安全地将string
而不是Uri
存储在数据库中。通常,理想的方法是使用一个简单的类作为数据库模型(具有string
属性),然后使用另一个在表示层中使用的类,而不是Uri
。这样,您可以很好地分离图层,并且可以在表示层上具有更实用的界面,不受数据库的限制。您甚至可以使用Automapper
之类的库轻松地从一种类型转换为另一种类型,而不必按属性执行属性。
但是,如果您不想处理此问题,还有其他选择。首先,在绑定string
的{{1}}时,您根本不必将Uri
转换为Source
。在XAML中内置了从Image
到string
的隐式类型转换,因此它应该按预期工作。
或者,您可以通过创建派生自Uri
的类来实现转换器。这可以覆盖IValueConverter
方法并从传入的Convert
中构建Uri
实例。然后将转换器注册为具有string
的资源,并在代码中使用它:
x:Key