2011-06-08 106 views
0

我想创建一个自定义面板,其中的项目呈现为内部带有关闭按钮(x)的按钮。我所做的,到目前为止是创建一个自ItemsControl派生的自定义控制,并设置模板itemspanel和ItemTemplate中是这样的:来自ItemsControl的WPF自定义面板

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

回答

0

RelativeSource.TemplatedParentControlTemplates,在这里你应该只绑定到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> 
+0

奇怪的,我试过了太多,但它没有”工作...... – Sys 2011-06-08 11:11:47

+0

然后将数据项可能没有所谓的'Name'公共财产。 – 2011-06-08 11:13:52

+0

它的确如此,请参阅上面的新信息 – Sys 2011-06-08 11:32:09