I have a usercontrol done by myself that has a dependency property that is a collection:

    private static readonly DependencyPropertyKey VerticalLinesPropertyKey = DependencyProperty.RegisterReadOnly("VerticalLines", typeof(VerticalLineCollection), typeof(DailyChart), new FrameworkPropertyMetadata(new VerticalLineCollection()));
    public static DependencyProperty VerticalLinesProperty = VerticalLinesPropertyKey.DependencyProperty;


    public VerticalLineCollection VerticalLines
    {
        get
        {
            return (VerticalLineCollection)base.GetValue(VerticalLinesProperty);
        }
        set
        {
            base.SetValue(VerticalLinesProperty, value);
        }
    }

I was filling this collection from XAML directly when a Window was using the control with code like:

<chart:DailyChart.VerticalLines>
    <VerticalLine ... ... ... />
</chart:DailyChart.VerticalLines>

Now, I removed this fixed initialization from XAML and I want to bind the collection to a property of the ViewModel but I get the error:

Error   1   'VerticalLines' property cannot be data-bound.
Parameter name: dp

Any ideas?

有帮助吗?

解决方案

In your XAML example, the parser sees that the VerticalLineCollection type implements IList and hence for each specified VerticalLine will create a VerticalLine object and then call Add on the collection itself.

However, when you attempt to bind the collection, the semantics become "assign a new collection to the VerticalLines property", which can't be done since this is a read-only dependency property. The setter on your property really should be marked as private, and in doing so you will get a compile-time error instead.

Hope this helps!

其他提示

I guess this is because of (True read-only dependency property).

As you have read only property you may change it to

        private static readonly DependencyPropertyKey VerticalLinesPropertyKey = DependencyProperty.Register("VerticalLines", typeof(VerticalLineCollection), typeof(DailyChart), new FrameworkPropertyMetadata(new VerticalLineCollection()));
        public static DependencyProperty VerticalLinesProperty = VerticalLinesPropertyKey.DependencyProperty;

Reflector gives the answer:

    internal static BindingExpression CreateBindingExpression(DependencyObject d, DependencyProperty dp, Binding binding, BindingExpressionBase parent)
    {
        FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata;
        if (((fwMetaData != null) && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly)
        {
            throw new ArgumentException(System.Windows.SR.Get(System.Windows.SRID.PropertyNotBindable, new object[] { dp.Name }), "dp");
        }
        ....

Hope this will work

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top