Search code examples
xamlwindows-phone-8formattingconditional-statements

Conditional text formatting XAML WP8


Is it possible to setup some form of conditional formatting of textblock controls in XAML so that the color of the text can be changed depending on the text (eg. Text = "good" then set to green, Text = "bad" then set text to red.)

I have tried some examples but they don't seem to work, presumably because WP8 works differently.


Solution

  • One simple way is in the view with DataTriggers like:

    Namespaces:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    

    Control:

    <TextBlock x:Name="TheText" Text="{Binding Blah}"/>
        <i:Interaction.Triggers>
          <ei:DataTrigger Value="Red"
                          Binding="{Binding Text, ElementName=TheText}">
              <ei:ChangePropertyAction PropertyName="Foreground"
                                       Value="Red" />
          </ei:DataTrigger>
          <ei:DataTrigger Value="Blue"
                          Binding="{Binding Text, ElementName=TheText}">
              <ei:ChangePropertyAction PropertyName="Foreground"
                                       Value="Blue" />
           </ei:DataTrigger>
        </i:Interaction.Triggers>
      </TextBlock>
    

    Or you could wire up the condition in code. Hope this helps.