Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 916
Mark Heath Avatar asked Nov 09 '10 17:11

Mark Heath


2 Answers

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.

like image 82
Muad'Dib Avatar answered Nov 05 '22 06:11

Muad'Dib


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.

like image 32
Dan Bryant Avatar answered Nov 05 '22 07:11

Dan Bryant