2011-04-22 51 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