IEnumerable DependencyProperty throws errors when set in XAML

三世轮回 提交于 2019-12-10 12:17:42

问题


I have a custom control Workspace that inherits from Control and within it is a DependencyProperty that I need to contain a user-specified IEnumerable<IFoo> (I have also tried making it an non-generic IEnumerable).

Public Shared ReadOnly FoosProperty As DependencyProperty = DependencyProperty.Register("Foos", GetType(IEnumerable(Of IFoo)), GetType(Workspace), New FrameworkPropertyMetadata())
Public Property Foos() As IEnumerable(Of IFoo)
    Get
        Return CType(Me.GetValue(FoosProperty), IEnumerable(Of IFoo))
    End Get
    Set(ByVal value As IEnumerable(Of IFoo))
        Me.SetValue(FoosProperty, CType(value, IEnumerable(Of IFoo)))
    End Set
End Property

Everything works perfectly when I create and set an array of IFoo in code but when I try to add them in XAML I get errors. If I add a single IFoo I get the error

  1. "'FooItem' is not a valid value for property 'Foos'."

at run time. If I try to add multiple IFoo items I get three errors at compile time

  1. The object 'Workspace' already has a child and cannot add 'FooItem'. 'Workspace' can accept only one child.
  2. Property 'Foos' does not support values of type 'FooItem'.
  3. The property 'Foos' is set more than once.

I read the errors to mean that WPF isn't converting the xaml to an array of items like it normally would. Here is how I'm trying to add the items in XAML

<Workspace>
    <Workspace.Foos>
        <FooItem />
        <FooItem />
    </Workspace.Foos>
</Workspace>

I have created similar DependencyProperties in the past and never had a problem so I'm guessing I'm missing something simple.

Thanks for any help!


回答1:


To be able to add multiple elements the collection property has to be IList or IDictionary. When it is IEnumerable XAML parser tries to assign first value to the property itself (instead of calling Add like with lists) and gets confused about consecutive items. This is the source of your errors.

Also, if you want to populate collection from XAML, make sure that your list is instantiated and not null to begin with, since XAML will not instantiate a list for you, it'll just call Add on it. So to avoid NullReferenceException, get rid of setter on your IList property and instantiate list from constructor.

It doesn't have to be dependency property:

private readonly ObservableCollection<FooItem> _foos = new ObservableCollection<FooItem>();

public ObservableCollection<FooItem> Foos
{
    get { return _foos; }
}


来源:https://stackoverflow.com/questions/3085676/ienumerable-dependencyproperty-throws-errors-when-set-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!