将值添加到 XAML 中的自定义集合属性

我正在尝试通过 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 中明确添加的值?


阿晨1998
浏览 177回答 1
1回答

长风秋雁

收藏型的可绑定属性的默认值应不使用的设置BindableProperty.Create方法,但在类的constuctor。这是一样的,其解释WPF依赖属性在这里。
打开App,查看更多内容
随时随地看视频慕课网APP