Conditional element style in XAML

I am creating an application for Windows Phone 8 that has a view model property:

public bool IsReply {get; set;}

In my xaml code, I would like to highlight two cases:

  • IsReply=True

    <Grid Margin="0,0,0,0">
    ...
    </Grid>
    
  • IsReply=False

    <Grid Margin="40,0,0,0">
    ...
    </Grid>
    

Basically, I would like to style the Grid element depending on the value of IsReply. I know that in WPF Style.Triggers exists, but apparently not in WP. The solution I have now is to have a duplicate copy of the entire grid code and set the visibility of each in the data converter. However, I think it should be easier to do.

+4
source share
3 answers

The easiest way is to use a style with triggers:

<Grid>
    <Grid.Style>
        <Style TargetType="Grid">
            <Setter Property="Margin" Value="40 0 0 0"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsReply}" Value="True">
                    <Setter Property="Margin" Value="0 0 0 0"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>
</Grid>
+5
source

margin grid MVVM

<Grid Margin="{Binding margin}">
 ...
</Grid>

if(IsReply)
  margin = new Thickness("0,0,0,0");
else
  margin = new Thickness("40,0,0,0");

.

0

You can use the DataTrigger, but you need to add these two links (right-click the "Links" link in your project and AddReference / Assemblies / Extensions / ...).

xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<Grid
    Margin="0">

    <i:Interaction.Triggers>

        <ei:DataTrigger
            Binding="{Binding Path=IsReply}"
            Value="True">

            <ei:ChangePropertyAction
                PropertyName="Margin"
                Value="0" />

        </ei:DataTrigger>

        <ei:DataTrigger
            Binding="{Binding Path=IsReply}"
            Value="False">

            <ei:ChangePropertyAction
                PropertyName="Margin"
                Value="40,0,0,0" />

        </ei:DataTrigger>

    </i:Interaction.Triggers>

</Grid>
0
source

All Articles