【发布时间】:2017-10-03 08:58:44
【问题描述】:
我有一个自定义控件,它由一个标签和一个自定义选取器组成。我需要将值绑定到 Xaml 中的 ItemSource 属性。这是我迄今为止尝试过的,但选择器中没有显示任何值。
编辑 2017 年 4 月 10 日:我已将示例项目上传到具有自定义控件的 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);
}
}
}
}
最后在我的视图中,我将 Itemsource 与这样的列表绑定。
<controls:CustomLabelWithPicker Grid.Row="1" Grid.Column="2"
LabelText="Bin Codes" ItemSource="{Binding BinCodes}"/>
但我没有看到任何绑定的值。感谢您的帮助
【问题讨论】:
-
可能在消费者视图模型中没有设置CustomLabelWithPicker的BindingContext,这就是它找不到ItemsSource绑定的原因
标签: xamarin xamarin.forms