UWP-C#:如何将Uri存入SQLite及加载GridView时字符串转Uri?
Hey there, let's work through this SQLite and System.Uri issue you're hitting—it's a super common problem because SQLite doesn't natively recognize .NET's System.Uri type. Let's fix both the save error and the load-time conversion step by step:
SQLite only supports basic data types (strings, integers, floats, etc.) out of the box, so it can't serialize/deserialize System.Uri directly. The solution is to store the Uri as a string in your database, and wrap it with a helper property for your app's logic.
If you're using SQLite-net (the most common library for .NET SQLite apps), use the [Ignore] attribute to tell SQLite to skip the Uri property, and add a string property to handle the actual database storage:
public class YourGridItem { // Primary key (adjust as needed for your model) public int Id { get; set; } // Other properties from your object public string ItemName { get; set; } // This string gets stored directly in SQLite public string ImageUriString { get; set; } // This Uri property is for your app to use—SQLite ignores it [Ignore] public Uri ImageUri { get { // Convert stored string back to Uri (handle null/empty cases) return string.IsNullOrEmpty(ImageUriString) ? null : new Uri(ImageUriString); } set { // Convert Uri to string for storage ImageUriString = value?.ToString(); } } }
When you save a new object, just assign the ImageUri property with the Uri from your ComboBox selection— the setter will automatically convert it to a string that SQLite can handle:
// Example: Get selected Uri from ComboBox var selectedImageOption = (YourComboBoxItemType)yourImageComboBox.SelectedItem; var newGridItem = new YourGridItem { ItemName = "My New Item", ImageUri = selectedImageOption.ImageUri }; // Insert into SQLite (using SQLite-net's async method) await yourDbConnection.InsertAsync(newGridItem);
The best part is that the conversion happens automatically when you load your objects. When you fetch items from the database, the ImageUri property's getter will turn the stored string back into a System.Uri for you:
// Load all items from SQLite var gridItems = await yourDbConnection.Table<YourGridItem>().ToListAsync(); // Assign to GridViewItem's Image control foreach (var item in gridItems) { if (item.ImageUri != null) { var image = new BitmapImage(item.ImageUri); // Assign this image to your GridViewItem's Image control yourGridViewItemImage.Source = image; } }
If You're Not Using SQLite-net
If you're using a different SQLite library (like System.Data.SQLite), you'll need to handle the conversion manually during insert and query:
- Insert: Convert the
Urito a string withuri.ToString()and pass that as the value to your SQL command. - Query: Read the string from the database result, then create a new
Uriwithnew Uri(storedString)when populating your object.
内容的提问来源于stack exchange,提问作者ZampTom

