I am trying to write a UserControl that will allow both single controls in it (like Label), as well as “layout” controls like StackPanel and friends.
I am having trouble doing that. The code I have works for single controls, but not for layout controls. I have a feeling this is an obvious fix, I am new to WPF. Here is the UserControl XAML:
<UserControl <!-- namespaces omitted for brevity -->>
<UserControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{TemplateBinding Content}" />
</DataTemplate>
</UserControl.ContentTemplate>
</UserControl>
When I try to use it like this:
<my:SpecialUserControl>
hello
</my:SpecialUserControl>
It’s fine. But when I try to do something like
<my:SpecialUserControl>
<StackPanel>
<!-- stuff -->
</StackPanel>
</my:SpecialUserControl>
I get an error in Visual Studio Intellisense saying
The specified value cannot be assigned to the collection. The following type was expected:
UIElement
And when I run the app (it builds), I get this exception at that place in the XAML:
‘Add value to collection of type
System.Windows.Controls.UIElementCollectionthrew an exception.’ Line numberxand line positiony.
What can I do to make my UserControl able to accept any type of content?
The
ContentPresentershould be a part of the ControlTemplate (<UserControl.Template>) of your control, not inside yourContentTemplate. I think that could be your problem.