BlackCap
BlackCap

Reputation: 1094

Programmatically position control in WPF

I am creating a karaoke program in WPF. Basically, I have a MediaElement which plays vidioes and such, and a StackPanel atop of that which I use to render stuff on top of the MediaElement.

I am trying to programmatically add a TextBlock to the StackPanel, which is going display the lyrics. The problem is that the TextBlock ends up in the top left corner no matter what I write.

Private LyricLabel As New TextBlock 

Sub New(Panel As StackPanel)
    With LyricLabel
        .Foreground = Brushes.White
        .FontFamily = New FontFamily("Verdana")
        .FontSize = 20

        .HorizontalAlignment = HorizontalAlignment.Stretch
        .VerticalAlignment = VerticalAlignment.Bottom
    End With

    Panel.Children.Add(LyricLabel)
End Sub

Also, I want a ball or something to jump from word to word. Is there a easy way to get the width of each of the words + the space between them, or do I have to calculate that by myself?

Upvotes: 0

Views: 575

Answers (1)

Alejandro
Alejandro

Reputation: 7813

It would be a better option to use a Grid and do that entirely in XAML. The Grid has the property that if many elements are in the same cell, they all overlap. So you put the MediaElement and a TextBlock together, with proper alignments and you're done:

<Grid>
    <MediaElement/>
    <TextBlock Text="{Binding CurrentLyric}" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0 0 0 30"/>
</Grid>

You just have to provide a property for dropping the current text to be shown for the binding to work, and it will adjust it for you.

Upvotes: 1

Related Questions