【发布时间】:2020-06-09 14:28:00
【问题描述】:
如何在自定义控件中显示选取器控件项?
我可以毫无问题地绑定到选择器的标题属性。 但是,我无法让 ItemsSource 绑定工作,以便我可以观察选择器的选择。
LabelPickerPair.xaml:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
x:Class="NewAssessment.UI.LabelPickerPair"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="ParentControl"
mc:Ignorable="d">
<ContentView.Content>
<StackLayout>
<Label FontSize="Medium" Text="{Binding Source={x:Reference ParentControl}, Path=LabelText}" />
<Picker
Title="{Binding Source={x:Reference ParentControl}, Path=Title}"
FontSize="Large"
ItemsSource="{Binding Source={x:Reference ParentControl}, Path=ItemsSource}"
</StackLayout>
</ContentView.Content>
</ContentView>
LabelPickerPair.xaml.cs:
namespace NewAssessment.UI
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LabelPickerPair : ContentView
{
public LabelPickerPair() => InitializeComponent();
public static BindableProperty TitleProperty = BindableProperty.Create(
propertyName: nameof(Title),
returnType: typeof(string),
declaringType: typeof(LabelPickerPair),
defaultValue: "",
defaultBindingMode: BindingMode.TwoWay);
public string Title
{
get { return (string)GetValue(TitleProperty); }
set
{
SetValue(TitleProperty, value);
}
}
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(
nameof(ItemsSource),
typeof(IList ),
typeof(LabelPickerPair),
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: OnItemsSourceChanged);
static void OnItemsSourceChanged(BindableObject bindable, object oldValue, object newValue)
{
var thisControl = bindable as LabelPickerPair;
if (oldValue != null)
thisControl.ItemsSource = oldValue as IList ;
if (newValue != null)
thisControl.ItemsSource = newValue as IList ;
}
public IList ItemsSource
{
get {
var items = (IList)GetValue(ItemsSourceProperty);
return items;
}
set { SetValue(ItemsSourceProperty, value); }
}
}
}
【问题讨论】:
-
我的回答对你有用吗?
标签: xamarin.forms