Switch data template based on value of bound data in Silverlight / WPF
Asked Answered
T

2

5

say I am using WPF or Silverlight and binding a ContentPresenter to an integer property:

<ContentPresenter Content={Binding Score} />

and if the score is 10 I want to display a gold star, and otherwise just display the number. So essentially I have two possible data templates:

<Path Fill="Gold" Data="..." />

<TextBlock Text="{Binding Score}" />

What is the best way to set this up? Is it to use a Binding Converter? Or bind to a different object that dynamically loads the appropriate data template xaml and makes the correct FrameworkElement depending on the value of Score? Or is there another trick I am missing - perhaps ContentPresenter isn't the right control to be using?

I wondered if you could do something like this, but it doesn't like the nested binding within the ContentTemplate value:

<StackPanel>
    <StackPanel.Resources>
        <DataTemplate x:Key="LowScore">
            <TextBlock Text="{Binding Path=Score}" Foreground="Red" />
        </DataTemplate>
        <DataTemplate x:Key="HighScore">
            <Path Fill="Gold" Data="M 0,0 l 10,0 l 5,-10 l 5,10 l 10,0 l -7,10 l 2,10 l -10,-5 l -10,5 l 2,-10 Z" />
        </DataTemplate>

    </StackPanel.Resources>
    <ContentPresenter Content="{Binding Score}" ContentTemplate="{StaticResource ResourceKey={Binding ScoreTemplate}}">
    </ContentPresenter>
</StackPanel>
Tjirebon answered 9/11, 2010 at 17:58 Comment(1)
hi Mark Heath , nice question but realy no answer , please let me know if you figured it out.Pyrone
E
10

you could use a template selector. Here is a nice tutorial on Switch On The Code. Basically, a template selector allows you to select the template for an item based on whatever conditions you want.

Estate answered 9/11, 2010 at 18:1 Comment(3)
very helpful tutorial. I somehow missed out on DataTemplateSelectorTjirebon
yeah, the dts is also really nice for things like templating list itemsPoisson
Perfect example of why link only answers are frowned upon on SO.Talya
A
1

Possible solutions:

  1. Create a DataTemplate with a StackPanel containing both control types and bind their Visibility (or use a DataTrigger) so that only one is visible at a time. This is fairly simple and can be good if there are not many states or the differences are small.

  2. Use a DataTemplateSelector and look up the DataTemplate by resource.

Arlo answered 9/11, 2010 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.