我在xaml中使用数据绑定的唯一经验来自Silverlight和RIA背景,这可能是我混淆的原因。我可以设计一个viewmodel如下:
public class ViewModelMyVehicles : ObservableCollection<ViewModelMyVehicle>
{
public ViewModelMyVehicles()
{
using (App.dbConn)
{
var results = App.dbConn.Query<ViewModelMyVehicle>("SELECT *
FROM MyVehicles;");
foreach (ViewModelMyVehicle r in results)
{
this.Add(r);
}
}
}
}
注意,我是如何从ObservableCollection继承的。在Xamarin,如果我这样做,我似乎无法弄清楚绑定。通常,我将绑定上下文设置为DomainDatasource(silverlight),将ItemSource设置为集合类本身(而不是集合属性)。以下是我看到每个人在Xamarin中使用的示例:
public class ViewModelMyVehicles
{
public ViewModelMyVehicles()
{
myVehicles = new ObservableCollection<ViewModelMyVehicle>();
using (App.dbConn)
{
var results = App.dbConn.Query<ViewModelMyVehicle>("SELECT *
FROM MyVehicles;");
foreach (ViewModelMyVehicle r in results)
{
myVehicles.Add(r);
}
}
}
public ObservableCollection<ViewModelMyVehicle> myVehicles { get; set; }
}
如果我这样做,绑定就像这样:
<ContentPage.BindingContext>
<local:ViewModelMyVehicles/>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<StackLayout Padding="15" Orientation="Horizontal">
<Label Text="My Garage: " />
<Picker x:Name="pickerMyVehicles" ItemsSource="{Binding myVehicles}" ItemDisplayBinding="{Binding Name}" SelectedIndex="1" />
</StackLayout>
</StackLayout>
</ContentPage.Content>
我想我的问题有两个: