DataTemplate for a DataType - how to override this DataTemplate in a particular ListBox?

雨燕双飞 提交于 2019-12-05 21:36:29

You can specify an ItemTemplate specifically for your ListBox:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- your template here -->
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Or alternatively, if you have already defined your DataTemplate in a ResourceDictionary somewhere:

<DataTemplate x:Key="MyTemplate">
      <!-- your template here -->
</DataTemplate>

Then you can reference it on the ListBox using:

<ListBox ItemTemplate="{StaticResource MyTemplate}" />

You do not need to write a template selector for either of these approaches to work


Example in response to comments

The example below demonstrates defining a default DataTemplate for a data type (in this case, String) for a window and then overridding it within a 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>

This produces the following UI:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!