isxaker
isxaker

Reputation: 9466

How to use the left margin value in a trigger?

I'm looking for a solution in xaml. I would like to have something like this:

<TextBlock HorizontalAlignment="Center">
    <TextBlock.Margin>
        <MultiBinding
            ...
        </MultiBinding>
    </TextBlock.Margin>
    <TextBlock.Triggers>
        <Trigger Property="Margin.Left"  Value="0" >
            <Setter Property="HorizontalAlignment" Value="Left" />
        </Trigger>
    </TextBlock.Triggers>
</TextBlock>

I mean set HorizontalAlignment = Left only if the left margin of the textblock equals to 0. But I am not allowed to use Margin.Left in the trigger condition. However I know that I can use a specific margin value but only in setters:

<Grid x:Name="myGrid" Grid.Row="1" Margin="30,0">
<Grid.Style>
  <Style TargetType="Grid">
    <Style.Triggers>
      <DataTrigger Binding="{Binding UI_Preferences.RightPanelPinned}" Value="true" >
        <Setter Property="Margin">
          <Setter.Value>
            <Thickness Left="200"/>
          </Setter.Value>
        </Setter>
      </DataTrigger>
    </Style.Triggers>
  </Style>
</Grid.Style>

Upvotes: 0

Views: 409

Answers (1)

Clemens
Clemens

Reputation: 128061

You may use a DataTrigger in a Style. The default HorizontalAlignment must also be set by the Style, not directly at the TextBlock, because that would have higher value precedence.

<TextBlock ...>
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Margin.Left,
                                               RelativeSource={RelativeSource Self}}" 
                             Value="0">
                    <Setter Property="HorizontalAlignment" Value="Left" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Upvotes: 2

Related Questions