自定义控件中的WPF自定义IList DependencyProperty行为奇怪

时间:2014-05-21 13:32:12

标签: wpf vb.net dependency-properties templatebinding

我想创建一个显示其他控件(按钮)列表的自定义控件。 我有一个名为Buttons的DependencyProperty

    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)))

并将其绑定在模板中,如下所示:

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

在XAML中使用控件的多个实例时,如此

        <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>

所有&#34;按钮&#34;将被分配到控件的最后一个实例,如下图所示:

Screenshot

我添加了一个自定义&#34;页脚&#34;财产以类似的方式运作,按预期运作。 我不知道我做错了什么,所以任何帮助都会受到赞赏。我觉得它与默认值&#34;新列表(控制权)&#34;有关。

可以在此处找到示例项目:CustomControl Example

非常感谢!

1 个答案:

答案 0 :(得分:0)

这回答了我的问题:stackoverflow.com/questions/16958476 / ...在ArrayList中嵌入按钮按预期工作

相关问题