Skip to content

Xaml Content Property Pitfalls #2939

Open
@mandalorianbob

Description

@mandalorianbob

If you try to create a XAML Content Property you run into an issue - the Property has to be a Dependency Property.

First you'll get a null ref in your designer, because the default value of the Collection is null.

Then the next step that anyone would do is make the default value of the Dependency Property an instance of the Collection. Bam, null ref solved!

And now you're in a world of hurt, because as per https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/custom-dependency-properties

When property metadata is assigned to a dependency property, the same metadata is applied to that property for every instance of the property-owner type or its subclasses. In property metadata, you can specify two behaviors:

A default value that the property system assigns to all cases of the property.
etc.

This causes weird issues, as you can imagine.

So in this section, there needs to be an explicit call out on how to actually create a Content Property, which requires three things:

  1. Creating a Dependency Property of the collection type (and possibly creating a class because List doesn't work)
  2. Assigning the ContentProperty to the control in question
  3. Setting the default instance in the constructor of the control - presumably prior to InitializeComponent.

I know the rest of this document doesn't refer to Dependency Objects or anything, but where else is this going to go? The ContentPropertyAttribute documentation literally says

For more info on XAML content properties, see "XAML content properties" section of XAML syntax guide.

But either way this needs to be front and center somewhere so the poor dev unlucky enough to run into this doesn't spend as much time as me on it.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

Labels

Pri2doc-bugfeedback is about something that is out of date, unclear, confusing, or broken in the articleplatform/techuwp/prod

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions