Search code examples
c#wpfbindingtriggerstextblock

WPF Trigger on TextBlock doesn't work C#


I want to make a centerized TextBlock, my first step is to try to make a trigger bind ActualWidth with Canvas.Left to see if it works, but unfortunately it doesn't work, it doesn't work after this:

LTest.HorizontalAlignement = Center;

I have also tried the c# code version of xmal, it doesn't work neither.

Anyone help me out? I have been troubled by this since one day.

It's in a Canvas

<TextBlock Canvas.Left="200" TextWrapping="Wrap" Text="Test222" Canvas.Top="200" FontSize="48" x:Name="LTest">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <Trigger Property="HorizontalAlignment" Value="Center">
                    <Setter Property="Canvas.Left" Value="{Binding RelativeSource={RelativeSource Self}
                    , Path=ActualWidth}"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Edit1:

It seems it doesn't work for

Canvas.Left

I have tested with

UIElement.Visibility

which is ok

Could anyone help me let it work with Canvas.Left?


Solution

  • You shold set Canvas.Left in your style , so the trigger manipulation this property wont get ignored since you set it on the control decleration

     <TextBlock TextWrapping="Wrap" Text="Test222" Canvas.Top="200" FontSize="48" x:Name="LTest">
             <TextBlock.Style>
                <Style TargetType="{x:Type TextBlock}">
                    <Setter Property="Canvas.Left" Value="200"/>
                    <Style.Triggers>
                        <Trigger Property="HorizontalAlignment" Value="Center">
                            <Setter Property="Canvas.Left" Value="{Binding RelativeSource={RelativeSource Self},Path=ActualWidth}"/>
    
                        </Trigger>
                    </Style.Triggers>
                </Style>
               </TextBlock.Style>
            </TextBlock>