TextBlock and TextAlignment=TextAlignment.Justify

BitSmithy 1,791 Reputation points
2024-04-30T11:26:15.7066667+00:00

Hello,

I have such issue:

When I set TextBlock.TextAlignment as TextAlignment.Center, the TextBlock's mouse events arent fired. If I set other TextAllignment all works

Code below:

XAML

    <Canvas x:Name="cnv">
     </Canvas>

C#

......        
public MainPage()
        {
            this.InitializeComponent();

            TextBlock tbl = new TextBlock();
            tbl.Text = "aaaaaaa";
            tbl.TextAlignment = TextAlignment.Justify;
            tbl.PointerEntered += Tbl_PointerEntered;

            cnv.Children.Add(tbl);
        }
.....
        private void Tbl_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

Is the way to fix this?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 15,446 Reputation points Microsoft Vendor
    2024-05-01T03:30:06.96+00:00

    Hi @BitSmithy ,

    Welcome to Microsoft Q&A!

    This is really an unexpected behavior. After researching, this should be an issue of Canvas, as other containers Grid, StackPanel are fine. After setting the width and height of the TextBlock everything works fine.

     TextBlock tbl = new TextBlock();
     tbl.Text = "aaaaaaa";
     tbl.TextAlignment = TextAlignment.Justify;
     tbl.Width = 100;
     tbl.Height = 50;
     tbl.PointerEntered += Tbl_PointerEntered;
     cnv.Children.Add(tbl);
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Cole Thompson 0 Reputation points
    2024-04-30T11:31:38.0733333+00:00

    The mouse events not to fire can be due to the way the TextAlignment property interacts with the layout and hit testing of the TextBlock. One potential solution is to wrap the TextBlock inside another container like a Grid or Border and set the TextAlignment property on that container instead. This will allow the TextBlock to remain centered visually but the container will handle the hit testing for mouse events. You can also handle the mouse events at the parent container level rather than directly on the TextBlock. This allows that the mouse events are captured regardless of the TextAlignment property.

    0 comments No comments