我有一个自定义控件,它由Label和Custom Picker组成。我需要将值绑定到Xaml中的ItemSource属性。这是我到目前为止所尝试过的,但是选择器中没有显示任何值。
编辑04/10/2017:我已将示例项目上传到github,该项目具有自定义控件:https://github.com/libin85/BindablePicker
这是CustomControl Xaml文件
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:WoolQ.Core.Controls;assembly=WoolQ.Core"
x:Class="WoolQ.Core.Controls.CustomLabelWithPicker">
<Grid x:Name="grid" VerticalOptions="Start">
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="45" />
</Grid.RowDefinitions>
<controls:RoundedFrame OutlineColor="Red" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" />
<Label x:Name="title" Text="" Grid.Row="0" Margin="5,5,5,0" Style="{StaticResource CustomConrtolLabelStyle}" />
<controls:BorderlessPicker x:Name="pickerValue" Title="_" Grid.Row="1" Style="{StaticResource CustomConrtolPickerStyle}" ItemsSource="{Binding ItemSource}">
</controls:BorderlessPicker>
</Grid>
在我背后的代码中:
public static readonly BindableProperty ItemSourceProperty =
BindableProperty.Create(nameof(ItemSource), typeof(List<string>), typeof(CustomLabelWithPicker), null);
public List<string> ItemSource
{
get
{
return (List<string>)GetValue(ItemSourceProperty);
}
set
{
SetValue(ItemSourceProperty, value);
}
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == nameof(ItemSource))
{
this.pickerValue.Items.Clear();
if (ItemSource != null)
{
foreach (var item in ItemSource)
{
this.pickerValue.Items.Add(item);
}
}
}
}
最后在我的View中,我将Itemsource与这样的List绑定。
<controls:CustomLabelWithPicker Grid.Row="1" Grid.Column="2"
LabelText="Bin Codes" ItemSource="{Binding BinCodes}"/>
但我没有看到任何绑定的值。感谢您的帮助
答案 0 :(得分:0)
在自定义选择器中尝试以下代码:
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(CustomPicker), null, BindingMode.TwoWay, null, OnItemsSourceChanged);
public IList ItemsSource
{
get { return (IList)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
private static void OnItemsSourceChanged(BindableObject bindable, object oldValue, object newValue)
{
var picker = (CustomPicker)bindable;
picker.ItemsSource = (IList)newValue;
}