views:

77

answers:

2

I have an abstract generic view-model that I use as a base-class for several other view-models. It is defined as follows:

public abstract class DiscreteViewModel<T>
{
    protected DiscreteItem<T> _selectedItem;
    ...
}

My DiscreteItem class is also generic, and as follows:

public class DiscreteItem<T>
{
    public T Display { get; set; }
    public double Value { get; set; }
}

My idea was to modify the values through the backing Value interface (because all the values of my items are doubles), but then display different types of things (colors, strings, images) using the Display property.

The problem arises when I try to create an editing Window to edit these view-models. My goal was to have a single Window defined in XAML, and use data templates and perhaps a DataTemplateSelector to provide different types of editing for the types of DiscreteItem. For example, if I see a color, I want to plug in a color-picker combo-box to edit it. And if I see a string, I want to plug in a simple text-box, etc. I quickly discovered that the support for generics in XAML is essentially non-existent. I cannot even instantiate a generic editing Window in XAML.

Obviously, I do not want to write an editor Window class for every possible type of DiscreteItem. That would result in a lot of duplicated code, and further duplication when someone else comes along and wants to edit some new type. I want a single editor that can be used for all DiscreteViewModel types. Does anyone have an elegant idea of how to do this? Is generics even the right way to go about this?

A: 

DataTemplate's are the preferred solution to this problem. You can put the templates in a ResourceDictionary and use them throughout your application.

Update per comment

You would not normally use Generics for this, instead you would combine DataTemplate's and a DataContext which would contain the item to edit.

<!-- Gross simplification -->
<Window x:Name="EditorWindow">
    <ContentControl Content="{Binding}"/>
</Window>
sixlettervariables
I know DataTemplates are the right way to solve the problem. You missed the point of the question; I am unable to use DataTemplates because I cannot even create a generic-type editor Window.
Charlie
A: 

i would not try and use generics here and i would make Display be of type object. you can then have a generic window that sets its content to be the discreteitem and let datatemplates do the rest.

Steve Psaltis