来自ItemsControl的WPF自定义面板

来自ItemsControl的WPF自定义面板,wpf,custom-controls,itemscontrol,Wpf,Custom Controls,Itemscontrol,我想创建一个自定义面板,其中项目被渲染为按钮,其中包含关闭按钮x。到目前为止,我所做的是创建一个从ItemsControl派生的自定义控件,并按如下方式设置itemspanel和itemtemplate的模板: XAML: 但是,当我设置ItemsSource时,我什么也得不到。有什么帮助吗 编辑 使用自定义控件: <cc:WorkspacePanel ItemsSource="{Binding Path=Workspaces}"/> 对于ControlTemplates,您只需通

我想创建一个自定义面板,其中项目被渲染为按钮,其中包含关闭按钮x。到目前为止,我所做的是创建一个从ItemsControl派生的自定义控件,并按如下方式设置itemspanel和itemtemplate的模板:

XAML:

但是,当我设置ItemsSource时,我什么也得不到。有什么帮助吗

编辑 使用自定义控件:

<cc:WorkspacePanel ItemsSource="{Binding Path=Workspaces}"/>
对于ControlTemplates,您只需通过不指定任何源绑定到DataContext:

{Binding Path=Name}
或者干脆

{Binding Name}
编辑:控件是一个自定义控件,我会放弃这种方法,我不知道它是否可以像那样工作,除非你手动编写很多代码,而不是通常为你编写的代码

当您创建控件且项目没有通用主题时,它应该已经创建了一个主题文件夹和一个generic.xaml,在该类中,您可以在样式中设置属性,而不是注意从默认ItemsControl获取模板和其他属性的BasedOn:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SandBox1.CustomControls">

    <Style TargetType="{x:Type local:WorkspacePanel}" BasedOn="{StaticResource {x:Type ItemsControl}}">
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <StackPanel IsItemsHost="True" Orientation="Horizontal" HorizontalAlignment="Left" />
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>

        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Button Content="{Binding Name}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

那么数据项可能没有名为Name的公共属性。我认为问题是您试图这样定义控件的外观,我认为这不起作用,您是否自己创建了XAML文件来为控件创建模板?是的,我自己创建了XAML,这不是第一次。
{Binding Path=Name}
{Binding Name}
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SandBox1.CustomControls">

    <Style TargetType="{x:Type local:WorkspacePanel}" BasedOn="{StaticResource {x:Type ItemsControl}}">
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <StackPanel IsItemsHost="True" Orientation="Horizontal" HorizontalAlignment="Left" />
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>

        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Button Content="{Binding Name}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>