Dennis Larisch
Dennis Larisch

Reputation: 573

XAML Textblock cannot be centered

I have a PopUp element in my XAML, inside this I have a Grid with a TextBlock inside.

The problem is now, that the text and the grid cannot be centered with Horizontal and Vertical Allignment...

XAML:

<Popup x:Name="Popup" Height="30px" VerticalAlignment="Top">
      <Grid Height="30px" 
            Background="Green" 
            Width="{Binding ActualWidth, ElementName=Popup}">
            <TextBlock VerticalAlignment="Center" 
                       HorizontalAlignment="Center" 
                       Foreground="White" 
                       Text="Änderungen wurden übernommen">
            </TextBlock>
      </Grid>
</Popup>

Preview in Visual Studio (which looks exactly like what I want to do): enter image description here Actual Result: enter image description here The TextBox inside the green PopUp is not centered as you can see. And I dont know why, maybe I´m missing something, but everything looks fine for me.

Upvotes: 3

Views: 79

Answers (1)

Justin XL
Justin XL

Reputation: 39006

You can manually subscribe to SizeChanged of your Popup like this -

Popup.SizeChanged += (s,e) => PopupGrid.Width = Popup.ActualWidth;

Update

I normally would create a UserControl popup that exposes a MessageText property so I can pass in dynamic text, and another IsOpen flag to toggle its visibility. I also disable it from hit testing and allow it to dismiss itself after a few seconds.

Hiding and showing should be done via Storyboards which are encapsulated inside the control.

In the end, this MessageControl should look like this -

<local:MessageControl IsOpened="{x:Bind MyToggle.IsOn, Mode=OneWay}" Message="Die Änderung wurde übernommen!" />

I have included a sample project here for your reference, and this is how it looks like -

enter image description here

Upvotes: 2

Related Questions