我试图通过XAML将值添加到自定义集合属性中:
<local:OnePageHeaderView>
<local:OnePageHeaderView.RightIconViewCollection>
<toolkit:IconView Source="one.png"></toolkit:IconView>
<toolkit:IconView Source="two.png"></toolkit:IconView>
<toolkit:IconView Source="three.png"></toolkit:IconView>
</local:OnePageHeaderView.RightIconViewCollection>
</local:OnePageHeaderView>
我确实设置了自定义属性和PropertyChanged
事件,如下所示:
public static readonly BindableProperty RightIconViewCollectionProperty = BindableProperty.Create(
propertyName: "RightIconViewCollection",
returnType: typeof(ObservableCollection<IconView>),
declaringType: typeof(OnePageHeaderView),
defaultValue: new ObservableCollection<IconView>(),
propertyChanged: RightIconViewCollectionPropertyChanged);
public ObservableCollection<IconView> RightIconViewCollection
{
get
{
return (ObservableCollection<IconView>)GetValue(RightIconViewCollectionProperty);
}
set
{
SetValue(RightIconViewCollectionProperty, value);
}
}
private static void RightIconViewCollectionPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (OnePageHeaderView)bindable;
control.RightIconViewCollection = (ObservableCollection<IconView>)newValue;
}
问题是RightIconViewCollection
始终是我设置的默认值,无论我要在XAML中添加多少个值。
我可以确认IconView
可以正常工作,因为我通过在后面的代码中手动添加IconViews进行了一些测试,并且可以正常工作。
为什么RightIconViewCollection
的值始终是defaultValue(new ObversableCollection()
),而不是我在XAML中明确添加的值?
编辑:测试用例
XAML:
<local:OnePageHeaderView
LeftIconViewSource="one.png">
<local:OnePageHeaderView.RightIconViewCollection>
<toolkit:IconView Source="two.png"></toolkit:IconView>
<toolkit:IconView Source="three.png"></toolkit:IconView>
</local:OnePageHeaderView.RightIconViewCollection>
</local:OnePageHeaderView>
OnePageHeaderView:
public OnePageHeaderView()
{
Init();
}
private void Init()
{
IconView leftIconView = new IconView
{
Source = LeftIconViewSource // LeftIconViewSource has value "one.png" which was assigned in XAML
};
ObservableCollection<IconView> iconViewCollection = new ObservableCollection<IconView>(RightIconViewCollection); // RightIconViewCollection has default value instead of assigned value in XAML
}
答案 0 :(得分:2)
不应使用BindableProperty.Create
方法而是在类的构造函数中设置集合类型可绑定属性的默认值。
与here中说明的WPF依赖项属性相同。
您将在此处找到如何实现集合类型可绑定属性的可行示例:
Xamarin - setting a collection to custom bindable property in XAML