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

I created several DataTemplates for some data types in my pet project. These data templates are really cool because they work like magic, magically transforming the appearance of data type instances whenever and wherever they appear in the user interface. Now I want to be able to modify the DataTemplate for these data types in one specific ListBox. Does this mean that I have to stop relying on WPF by automatically applying a data template to data types and assigning x: Key to DataTemplates, and then apply the / ItemTemplate template in the user interface with this key?

The ListBox contains elements of various DataTypes (all obtained from a common base class) and, as of now, everything works magically without specifying a TemplateSelector, since the correct template is selected by the actual data type of the element in the listBox. If I went to use x: Key to use DataTemplates would I need to write a TemplateSelector?

I am new to this and am only experimenting with DataTemplates. One moment, I think, wow, how cool! And then I need a different data template for the same data type in a different list and oooh, I can not do this :-) Help please?

+3
source share
1 answer

You can specify ItemTemplatespecifically for your ListBox:

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

, , DataTemplate ResourceDictionary -:

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

ListBox, :

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


DataTemplate ( , String) :

<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>

:

Example Display

+3

Source: https://habr.com/ru/post/1772631/


All Articles