2010-08-13 46 views
5

我對WPF世界很陌生,我在ItemsControl中遇到了模板項目的一些問題。我需要的是在ItemsControl(或類似的東西)中模板元素(主要是按鈕)。ItemTemplate:ListBox vs ItemsControl

如果我用下面的XAML代碼...

<ItemsControl> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate DataType="{x:Type Button}"> 
       <Border BorderBrush="AliceBlue" 
         BorderThickness="3"> 
        <TextBlock Text="Templated!"/>   
       </Border> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    <Button>Not templated</Button> 
    <TextBlock>Text not templated</TextBlock> 
</ItemsControl> 

...我得到這樣的結果:http://img444.imageshack.us/img444/2167/itemscontrolnottemplate.gif

的ItemsControl模板並不適用於無論是按鈕也不對TextBlock控制。如果我改變ItemsControl的列表框這樣的:

<ListBox> 
    <ListBox.ItemTemplate> 
     <DataTemplate DataType="{x:Type Button}"> 
       <Border BorderBrush="AliceBlue" 
         BorderThickness="3"> 
        <TextBlock Text="Templated!"/>   
       </Border> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
    <Button>Not templated</Button> 
    <TextBlock>Text not templated</TextBlock> 
</ListBox> 

...然後我得到這個結果:img814.imageshack.us/img814/6204/listboxtoomuchtemplatin.gif

現在該模板適用於BOTH子控件(即使我將數據類型設置爲僅限於)。

回答

15

這很難推斷出你想要做什麼,而是看是否可以幫助...

一個普通的,如果他們已經UI元素舊ItemsControl不會換的孩子在一個容器中。另一方面,要求其子女被包裹在ListBoxItem中。

如果物品被包裝,則將應用ItemTemplate。如果物品未被包裝,ItemTemplate可能不存在。

您幾乎總是希望將數據項添加到您的ItemsControl,而不是UI元素。然後,您將DataTemplate與這些數據元素相關聯,以定義用於呈現它們的UI元素。

我認爲解釋你的最終目標是必要的,以幫助進一步。