Reputation: 75
I have a control that wants to adjust its style based on a variable within its datacontext. As is I have a ListBox holding a list of contacts who are either customer or vendor.
Each contact has a name and is set to customer or vendor. Each customer has a recent purchase and an email whereas each vendor has a company name, fax, and sales info. So basically I'd like to have two separate styles based on the contact_type variable.
How could I do this?
Upvotes: 0
Views: 190
Reputation: 4568
If you subclass your Contact
class into Customer
and Vendor
types, then you can simply define a different DataTemplate
for each type, and WPF will automatically use the correct one. They can be included as resources of the ListBox
as in the sample below, or higher up in the tree.
<ListBox ItemsSource="...">
<ListBox.Resources>
<DataTemplate DataType="{x:Type Customer}">
...
</DataTemplate>
<DataTemplate DataType="{x:Type Vendor}">
...
</DataTemplate>
</ListBox.Resources>
</ListBox>
Upvotes: 0
Reputation: 45096
That is exactly what a DataTemplateSelector is designed to do
And really the template should be based on the class - not a variable
If the customer and vendor have some common properties then have them each implement the common interface
Upvotes: 1