【发布时间】:2016-09-05 19:58:50
【问题描述】:
我正在开发一个 Xamarin 项目,我需要使用选择器,因此 Xamarin 的本机选择器没有 ItemsSource。我找到了一个几乎可以正常工作的实现,这里是:
using System;
using System.Collections;
using System.Linq;
using Xamarin.Forms;
namespace AnyNameSpace.Mobile.CustomControls
{
public class BindablePicker : Picker
{
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create(
"ItemSource",
typeof (IEnumerable),
typeof (BindablePicker),
default(IEnumerable),
BindingMode.TwoWay,
propertyChanged: OnItemsSourceChanged);
public static BindableProperty SelectedItemBindableProperty =
BindableProperty.Create(
"SelectedItemBindable",
typeof (object),
typeof (BindablePicker),
default(object),
BindingMode.TwoWay,
propertyChanged: OnSelectedItemChanged);
public IEnumerable ItemsSource
{
get { return (IEnumerable) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public object SelectedItemBindable
{
get { return GetValue(SelectedItemBindableProperty); }
set { SetValue(SelectedItemBindableProperty, value); }
}
public BindablePicker()
{
SelectedIndexChanged += OnSelectedIndexChanged;
base.Title = "Seleccione"; // Here I want a custom title, but this is ignoring me :(
}
private static void OnItemsSourceChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var picker = bindable as BindablePicker;
if (picker?.Items == null) return;
picker.Items.Clear();
if (newvalue == null) return;
foreach (var item in ((IEnumerable)newvalue).Cast<object>().Where(item => item != null))
picker.Items.Add(item.ToString());
}
private void OnSelectedIndexChanged(object sender, EventArgs eventArgs)
{
if (Items != null && (SelectedIndex < 0 || SelectedIndex > Items.Count - 1))
SelectedItemBindable = null;
else if (Items != null) SelectedItemBindable = Items[SelectedIndex];
}
private static void OnSelectedItemChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var picker = bindable as BindablePicker;
if (newvalue == null) return;
if (picker?.Items != null) picker.SelectedIndex = picker.Items.IndexOf(newvalue.ToString());
}
}
}
所以问题是:当在 XAML 甚至 C# 上设置 Title 属性时,它总是在 Title 属性中显示“选择一个项目”,我试图在构造函数中设置 Picker 的 Title,但不起作用。
如果有任何帮助,我将不胜感激,谢谢。
【问题讨论】:
标签: c# xaml xamarin.forms