来自ItemsControl的WPF自定义面板

时间:2011-06-08 10:10:32

标签: wpf custom-controls itemscontrol

我想创建一个自定义面板,其中项目呈现为按钮,内部有关闭按钮(x)。我到目前为止所做的是创建一个自定义控件,该控件派生自ItemsControl,并设置itemspanel和itemtemplate的模板,如下所示:

XAML:

<ItemsControl x:Class="SandBox1.CustomControls.WorkspacePanel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel IsItemsHost="True" Orientation="Horizontal" HorizontalAlignment="Left"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Name}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

代码隐藏:

public partial class WorkspacePanel : ItemsControl
{
    public WorkspacePanel()
    {
        InitializeComponent();
    }
}

然而,当我设置ItemsSource时,我什么都没得到。有什么帮助吗?

修改

使用自定义控件:

<cc:WorkspacePanel ItemsSource="{Binding Path=Workspaces}"/>

工作区的类型为ObservableCollection<WorkspaceModel>,WorkspaceModel为:

public class WorkspaceModel
{
    public WorkspaceModel(string name, bool isActive)
    {
        this.Name = name;
        this.IsActive = isActive;
    }

    public bool IsActive  { get; set; }
    public string Name { get; set; }
}

1 个答案:

答案 0 :(得分:0)

RelativeSource.TemplatedParent适用于ControlTemplates,在这里您应该通过不指定任何来源绑定到DataContext:

{Binding Path=Name}

或只是

{Binding Name}

编辑:作为自定义控件的控件我会放弃这种方法(我不知道它是否可以工作),除非你手动编写很多代码VS通常会写对你而言。

当您创建控件并且您的项目没有通用主题时,它应该已创建Themes文件夹和Generic.xaml,在该类中您可以设置样式中的属性(请注意BasedOn获取默认ItemsControl中的模板和其他属性:

<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>
相关问题