我对WPF世界还比较陌生,在使用ItemsControl时遇到了一些问题。我需要为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 < p > ItemsControl 没有将模板应用到 Button 或 TextBlock 控件。如果我像这样将 ItemsControl 更改为 ListBox:
<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
现在模板被应用于所有子控件(即使我仅将DataType设置为Button)。