5

Possible Duplicate:
XAML Conditional Compilation

I am new to WPF. I just need to write a small piece of code in xaml, for which i need to know the if condition equivalent in WPF. Can anybody here help in that?

Community
  • 1
  • 1
CNG
  • 65
  • 1
  • 1
  • 5
  • You should be using the code behind if you want to write conditionals. What exactly are you trying you to do here? – Rohith Dec 11 '09 at 14:30
  • I had a similar question today, but didn't find the accepted answer here useful. I asked again, and got an answer, here: https://stackoverflow.com/questions/68499748/how-to-write-an-if-user-control-for-wpf-xaml – Ben Jul 23 '21 at 17:46

1 Answers1

16

Are you after something like, "If (x == 1), make the background of this control blue"? If that is what you are after, you could use data triggers. Here is an example that changes the background color of a control conditionally based on some data. In this example, I made it part of a style and used it later in some controls.

<UserControl.Resources>
    <Style x:Key="ColoringStyle" TargetType="{x:Type DockPanel}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=Coloring}" Value="Red">
                <Setter Property="Background" Value="#33FF0000"></Setter>
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=Coloring}" Value="Blue">
                <Setter Property="Background" Value="#330000FF"></Setter>
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=Coloring}" Value="White">
                <Setter Property="Background" Value="#33FFFFFF"></Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

If 'Coloring' changes values to 'Red', 'Blue', or 'White', it will update the background property of the DockPanel accordingly.

<DockPanel Style="{StaticResource ColoringStyle}">
     ...
</DockPanel>
Ben Collier
  • 2,632
  • 1
  • 23
  • 18