views:

190

answers:

3

In one of my first attempts with WPF I went a bit too far:

I have an object that needs a different DataTemplate depending on one of its properties. In other words if (object.property=="multi") then the template should be a combo, etc.

Now I 've went ahead and obviously used a DataTemplateSelector to apply the required template. And in runtime that works. In design-time vs2008 designer complains because the DataTemplateSelector uses Application.Current.MainWindow.FindResource in order to find the appropriate template to apply and obviously Application.Current in design time is not my application, so the resource cannot be found, so the designer throws an exception.

Given that I would like other people to be able to change the templates, I really need design-time support for this.

Is there a solution to my problem? Is my whole approach completely flawed?

A: 

You could add a dependency property to your template selector for each kind of template and reference the templates in XAML:

<local:MyTemplateSelector x:Key="myTemplateSelector"
  Template1="{StaticResource tpl1}"
  Template2="{StaticResource tpl2}"
/>

Or, just instantiate and assign the template selector in the code behind.

Sergey Aldoukhov
Thanks for the answer.The first solution could work but it's impractical given the number of templates I have.The second solution doesn't seem to work, unless there's something I 'm not getting.
christos
A: 

This is just off the top of my head so i'm not sure if it works, but what about using datatriggers and assign the appropriate template with a setter.

Something like"

<ContentControl>
        <ContentControl.Style>
            <Style TargetType="{x:Type ContentControl}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Property}" Value="multi">
                        <Setter Property="ContentTemplate" Value="{StaticResource templateKey}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
        ...
    </ContentControl>
AndyG
A: 

I think I have found the answer to my question (though it has problems of its own).

The DataTemplateSelector should have public properties to hold the possible templates. When you instantiate the DataTemplateSelector in XAML you pass it the relevant templates, something like

<TemplateSelector MultiTemplate1=Template1, MultiTemplate2=Template2/>

This achieves design-time support. On the other hand it requires that you know what are the possible templates when you instantiate the selector, which is not always the case.

christos