Switch (Select) statement in Xaml Binding?

Shimmy Weitzhandler picture Shimmy Weitzhandler · Dec 6, 2010 · Viewed 10.9k times · Source

Is there a way to create a conditional binding in XAML?

Example:

<Window x:Name="Me" DataContext="{Binding ElementName=Me}">
    <TextBlock>
        <TextBlock.Text>
            <SelectBinding Binding="{Binding MyValue}">
                <Case Value="Value1" Value="value is 1!">                
                <Case Value="Value2" Value="value is 2!">                
                <Case Value="Value3" Value="value is 3!">                
            </SelectBinding >
        </TextBlock.Text>
    </TextBlock>
</Window>

Bottom line, I want to set a TextBlock value according to another value of Binding, that can be of a list of cases where each case (or cases) is addressed to the appropriate output/setter.

Maybe I can use a DataTrigger in my case, I just don't know exactly how I am gonna do it, since I am not using any DataTemplate here.

Update
In my scenario, I am having a UserControl that has several controls. I want that according to a certain property in the UserControl.DataContext data-item, other controls in the user control should get affected accordingly. Basically same as my example above just that each case leads to a list of Setters.

Answer

Dean Chalk picture Dean Chalk · Dec 6, 2010

use a DataTrigger

(EDITED - original had slight mistake)

<TextBlock>
  <TextBlock.Style>
    <Style>
      <Style.Triggers>
        <DataTrigger Binding="{Binding MyValue}" Value="Value1">
          <Setter Property="TextBlock.Text" Value="value is 1!"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding MyValue}" Value="Value2">
          <Setter Property="TextBlock.Text" Value="value is 2!"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding MyValue}" Value="Value3">
          <Setter Property="TextBlock.Text" Value="value is 3!"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBlock.Style>