我正在处理一个 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 但不起作用。
如果有任何帮助,我将不胜感激,谢谢。
最佳答案
通过 Xaml 或代码设置 Title-Property 效果很好。 我刚刚在一个小项目中对此进行了测试。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:control="clr-namespace:AnyNameSpace.Mobile.CustomControls"
x:Class="TestApp.BindablePickerTestPage">
<control:BindablePicker Title="MyTitle"></control:BindablePicker>
</ContentPage>
关于c# - 可绑定(bind)选择器的标题不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37145318/