以下是相关代码:
public class SelectClientPage : ContentPage
{
public SelectClientPage(ClientResult[] clients)
{
this.BindingContext = new SelectClientViewModel(this, clients);
var layout = new StackLayout { Padding = 20 };
var list = new ListView
{
ItemTemplate = new DataTemplate(typeof(ClientListTemplate)),
BackgroundColor = MobileColor.LightOrigamiBlue.ToFormsColor(),
HasUnevenRows = true,
};
list.SetBinding(ListView.ItemsSourceProperty, "Clients");
list.SetBinding(ListView.SelectedItemProperty, "SelectedItem");
layout.Children.Add(list);
this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
this.Content = layout;
}
public class ClientListTemplate : ViewCell
{
protected override void OnBindingContextChanged()
{
ClientResult client = (ClientResult)this.BindingContext;
var pad = new ContentView {
Padding = new Thickness(5,5),
Content = new Label
{
Text = client.name,
TextColor = Color.White,
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(ListView))
}
};
this.View = pad;
}
}
}
public class SelectClientViewModel : ViewModelBase
{
public SelectClientViewModel(Page page, ClientResult[] clients) : base(page)
{
this._Clients = clients;
}
private ClientResult[] _Clients;
public ClientResult[] Clients { get { return _Clients; } }
private object _SelectedItem = null;
public object SelectedItem
{
get { return _SelectedItem; }
set { this.SetProperty(ref _SelectedItem, value); }
}
//... rest truncated //
}
此代码在iOS或Android中运行良好。但是,在UWP中,它在ClientListTemplate类的这一行中失败:
ClientResult client = (ClientResult)this.BindingContext;
它失败的原因是因为传入ViewCell的BindingContext是SelectClientViewModel类型,它最初被分配给内容页面的BindingContext。因此它会抛出一个无效的强制转换异常。
还有其他人遇到过这个吗?我是关于Xamarin.Forms v2.3.3.175。
感谢。