2011-04-22 98 views
0

我已经模板化了一段时间的WPF列表框仍然改变内容,但我想知道是否有办法有一个适用于ListBoxItem的模板ListBox中的所有项目,但也有ItemTemplateSelector改变容器的内容。列表框模板:如何创建一个通用模板,但基于项目

我有字符串和图像的列表,我想显示它们唯一地使得图像显示用框和字符串在文本框显示要被编辑。我制作了一个ItemTemplateSelector,并根据类型选择模板。不过,我想添加一些控件,如要删除的按钮和用于向两个模板显示选择的复选框。

我知道我可以两个对象同时添加到模板字符串或图像,但我希望它能够扩展,而不必添加的每个我添加模板的时间。有什么想法吗?

回答

1

您可以使用ItemContainerStyle覆盖ListBoxItemsTemplate(可能不是我会做的)。

或者,也可以定义一个ItemTemplate,其利用ContentControl,例如帧的模板

<ListBox ItemsSource="{Binding Data}"> 
    <ListBox.Resources> 
     <!-- The frame that is applied to all items --> 
     <ControlTemplate x:Key="commonFrameTemplate" TargetType="{x:Type ContentControl}"> 
      <Border BorderBrush="Red" BorderThickness="2" CornerRadius="5" Padding="5"> 
       <StackPanel> 
        <CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}"/> 
        <ContentPresenter /> <!-- Where the individual templates end up --> 
        <Button Content="Delete"/> 
       </StackPanel> 
      </Border> 
     </ControlTemplate> 

     <!-- Define templates without using a x:Key but setting the DataType, 
      the template will automatically be applied, no need for a 
      template-selector --> 
     <DataTemplate DataType="{x:Type local:Employee}"> 
      <TextBlock Text="{Binding Name}" Foreground="Red"/> 
     </DataTemplate> 

    </ListBox.Resources> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <!-- By setting the content to {Binding} the templating is delegated 
       in a way, if you must use a selector, define one here as 
       ContentTemplateSelector --> 
      <ContentControl Template="{StaticResource commonFrameTemplate}" 
          Content="{Binding}"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
+0

这是一个很棒的想法。我的另一个想法是做一个用户控件,这是一个ContentControl中和其他地方定义它,但我觉得这正是我一直在寻找。我特别喜欢xaml接近模板,所以你可以告诉看看代码是什么。 – maschall 2011-05-04 13:41:32