Question

Is it possible to use different templates for items in the ListBox in WPF basing on type of item?

Say, we have base class:

class BaseItem
{
}

And then two more:

class IntItem : BaseItem
{
     public int I { get; set; }
}

class StringItem : BaseItem
{
     public string S { get; set; }
}

Then, I may build an ObservableCollection of BaseItems and attach to the ListBox. I would like to display the text as a textbox and the integer as a tracker, for instance. Is it possible? If so, how can I do it?

Was it helpful?

Solution

Of course this is possible.

Just define a DataTemplate for each Type in your ListBox Resources:

<DataTemplate DataType="{x:Type IntItem}">
    ....
</DataTemplate>
<DataTemplate DataType="{x:Type StringItem}">
    ....
</DataTemplate>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top