Search code examples
wpfvb.netdependency-propertiestemplatebinding

WPF custom IList DependencyProperty in custom control behaving oddly


I want to create a custom control that displays a list of other controls (Buttons). I have a DependencyProperty called Buttons

    Public Property Buttons As IList
    Get
        Return GetValue(ButtonsProperty)
    End Get

    Set(ByVal value As IList)
        SetValue(ButtonsProperty, value)
    End Set
End Property

Public Shared ReadOnly ButtonsProperty As DependencyProperty = _
                       DependencyProperty.Register("Buttons", _
                       GetType(IList), GetType(CustomControl1), _
                       New PropertyMetadata(New List(Of Control)))

and am binding it in the Template like this:

    <ItemsControl  
         ItemsSource="{TemplateBinding Buttons}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ContentControl Content="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

When using multiple instances of the control in XAML like this

        <StackPanel>
        <local:CustomControl1>
            <local:CustomControl1.Header>
                <Label Content="Header 1"/>
            </local:CustomControl1.Header>
            <Label Margin="14" Content="Content 1"/>
            <local:CustomControl1.Buttons>
                <Button Content="Button 1 A"/>
                <Button Content="Button 1 B"/>
            </local:CustomControl1.Buttons>
        </local:CustomControl1>
        <local:CustomControl1>
            <local:CustomControl1.Header>
                <Label Content="Header 2"/>
            </local:CustomControl1.Header>
            <Label Margin="14" Content="Content 2"/>
            <local:CustomControl1.Buttons>
                <Button Content="Button 2 A"/>
                <Button Content="Button 2 B"/>
            </local:CustomControl1.Buttons>
        </local:CustomControl1>
    </StackPanel>

All "buttons" will be assigned to the last instance of the control like in this picture:

Screenshot

I have added a custom "Footer" property in similar fashion which is working as expected. I have no Idea what I am doing wrong, so any help would be appreciated. I have a feeling that it has to do with the Default value "New List(Of Control)".

The Example Project can be found here: CustomControl Example

Thank you very much!


Solution

  • This answered my question: stackoverflow.com/questions/16958476/… Embedding the buttons inside an ArrayList works as expected