Search code examples
wpfwpf-controlsuielement

Adding UIElements to custom control (WPF)


How can I create a custom control which takes a list of UIElements and renders them according to some logic?

Because it will handle a list of UIElements, the best way of adding controls will be the same as for, i.e. ListBox or ComboBox.

<local:SomeControl>
    <Button Content="First"/>
    <Label Content="Something other"/>
</local:SomeControl>

Here is the user control's XAML:

<UserControl x:Class="_2009_07_22_Wpf_Smooth_Scroller.SomeControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             MinHeight="100" MinWidth="100">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Label Content="Some title"/>

        <!-- The inner UIElement to add content to  -->
        <Canvas x:Name="innerPanel" Grid.Row="1"/>

    </Grid>
</UserControl>

How can I, for instance, place i-th control to location X = 50 * i, Y = 40 * i ?


Solution

  • What you've described is a WPF Panel:

    Use Panel elements to position and arrange child objects in Windows Presentation Foundation (WPF) applications.

    That is, you could subclass Panel and arrange your children according to your custom logic.