如何绑定SQLite的完整响应?
我正在我的C#文件中创建一个ListView
。 但不是我想要添加我从sqlite获得的数据,带有数据绑定的xaml文件,所以我仍然可以使用xaml编辑布局。 因此,sqlite的每个响应都需要添加为标签( )。
我的问题:如何将GetCategoryByMenuID
的响应绑定到TextCell Text="{Binding Name}"
?
xaml页面(CategoriePage.xaml):
后端/ C#(CategoriePage.xaml.cs):
namespace AmsterdamTheMapV3 { public partial class CategoriePage : ContentPage { public CategoriePage(String txt) { InitializeComponent(); var layout = new StackLayout { Padding = new Thickness(5, 10) }; int page = Int32.Parse(txt); this.Content = layout; var categories = App.Database.GetCategoryByMenuID(page); var datatemplate = new DataTemplate(() => { var nameLabel = new Label(); nameLabel.SetBinding(Label.TextProperty, "Name"); //nameLabel.SetBinding(Label.idProperty, "Name"); return new ViewCell { View = nameLabel }; }); var listView = new ListView { ItemsSource = categories, ItemTemplate = datatemplate }; layout.Children.Add(listView); } } }
GetCategoryPage函数:
public List GetCategoryByMenuID(int menuID) { lock (locker) { return db.Table().Where(x => x.Menu_ID == menuID).ToList(); } }
特定
更新后面的代码
namespace AmsterdamTheMapV3 { public partial class CategoriePage : ContentPage { public CategoriePage(string txt) { InitializeComponent(); this.Appearing += (s,e) => { if(NotInDesignMode) { int page = 0; if(int.TryParse(txt, out page)){ var categories = App.Database.GetCategoryByMenuID(page); this.listView.ItemsSource = categories; } } }; } bool NotInDesignMode { get { return Application.Current != null; } } } }
你可以用丑陋且快速实现的方式(在你的GetCategoryByMenuID方法中,按ID运行更新名称,它将在类别上运行)。
或者通过创建一个基于menuID而不是基于索引的集合作为常规列表。
public class CategoriesCollection : KeyedCollection { protected override int GetKeyForItem(T item) { return (item as Category).Id; } /// /// Method to get the index into the List{} in the base collection for an item that may or may /// not be in the collection. Returns -1 if not found. /// protected override int GetItemIndex(T itemToFind) { int keyToFind = GetKeyForItem(itemToFind); return BaseList.FindIndex((T existingItem) => GetKeyForItem(existingItem).Equals(keyToFind)); } }
sql应该可以存储/检索任何icollection,所以当你不能使用字典时,这应该工作。 至少它在sqlite中为我工作(在我从sqliteAPI转移到entityframework之前)