2
votes

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?

3
How the second approach does not work? If the template selector is instantiated in the code behind, the markup has no knowledge of it and the design time should be fine.Sergey Aldoukhov
I doesn't work, I think, because at design-time any user code in the constructor of Window or App for example is not executed. See also here west-wind.com/weblog/posts/791658.aspxchristos

3 Answers

2
votes

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.

0
votes

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

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.