可以具體指定ItemTemplate
您ListBox
:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- your template here -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
或者,如果你已經在ResourceDictionary
定義了DataTemplate
地方:
<DataTemplate x:Key="MyTemplate">
<!-- your template here -->
</DataTemplate>
然後,你可以參考它的使用:
<ListBox ItemTemplate="{StaticResource MyTemplate}" />
你並不需要編寫這兩種方法的模板選擇工作
例響應意見
下面的例子演示定義了默認的DataTemplate
的數據類型(在這種情況下,String
)的一個窗口,然後overridding一個ListBox中:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type sys:String}">
<Rectangle Height="10" Width="10" Margin="3" Fill="Red" />
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Rectangle Height="10" Width="10" Margin="3" Fill="Blue" />
</DataTemplate>
</ListBox.ItemTemplate>
<sys:String>One</sys:String>
<sys:String>Two</sys:String>
<sys:String>Three</sys:String>
</ListBox>
</Grid>
</Window>
這親duces以下界面:
的DataTemplate中我有我的ResourceDictionary是針對某一特定數據類型和WPF應用模板,該數據類型的任何實例無論自動顯示出來,所以即使當我設置的ItemTemplate列表框到{x:Null},項目仍然顯示模板。 – 2010-11-02 10:56:20
如果您將'ItemTemplate'設置爲'{x:Null}',我希望它使用默認模板 - 如果您明確指定模板,是否還會得到相同的行爲? – 2010-11-02 11:00:36
感謝您的留言。我設法將一個不同的ItemTemplate應用於昨天在'特殊'列表框中的元素,我不記得究竟是什麼問題,這是微妙的。但問題的一部分仍然存在 - 因爲列表框中有三種不同類型的對象。對於這些數據類型,我指定了一個DataTemplate,現在,在一個特定的列表框中,我希望這些數據類型看起來不同。我可以明確地設置ItemTemplate,然後覆蓋之前提到的數據模板,然而,然後我只能得到所有三種類型的一個數據模板。 – 2010-11-03 09:54:06