mbl
mbl

Reputation: 925

How to fill a StackPanel inside of a UserControl?

I am creating a custom panel which is basically just a fancier StackPanel with some added functionality. I was going to use a UserControl which contains a StackPanel but I don't know how to make my UserControl accept content to fill it's StackPanel.

This is what I'm trying:

<UserControl
    x:Class="transformations.fold_panel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:transformations"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Vertical">
        <Button Content="First" />
        <ContentControl Content="{x:Bind Content, Mode=OneWay}"></ContentControl>
    </StackPanel>
</UserControl>

Usage:

<local:fold_panel>
     <Button Content="Second" />
</local:fold_panel>

When I try this I get the following error: WinRT originate error - 0x80070057 : 'The parameter is incorrect.'.

Upvotes: 0

Views: 34

Answers (1)

mm8
mm8

Reputation: 169200

You can't bind the Content of a StackPanel in a UserControl's Content to the Content property of the same UserControl. This will introduce a circular reference.

In your example, the Content property of the fold_panel UserControl will be set to the StackPanel that you defined in the XAML markup.

If you want to be able to set the Content of the ContentControl in the StackPanel, you should add a custom dependency property to the fold_panel class and bind the Content property of the ContentControl to this one:

<ContentControl Content="{x:Bind CustomContent, Mode=OneWay}" />

You can then set your custom property something like this:

<local:fold_panel>
    <local:fold_panel.CustomContent>
        <Button Content="Second" />
    <local:fold_panel.CustomContent>
</local:fold_panel>

But if you really want a custom StackPanel, you should create a class that inherits from StackPanel rather than UserControl.

Upvotes: 1

Related Questions