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>
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.
Possible solutions:
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.
Use a DataTemplateSelector and look up the DataTemplate by resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With