TripleAntigen
TripleAntigen

Reputation: 2299

WPF control alignment is wrong when dynamically added

Hi I thought I could solve this easily but it is driving me crazy.

I am using a UserControl to house a video player control based on VLC, along with play and stop buttons etc. I then place the UserControl on my main form. if the UserControl is declared in XAML it behaves normally.

I decided to rewrite the code to instantiate my UserControl dynamically, in case I need to destroy it and create another on the fly. But when I do the video moves to the top of its container instead of the middle.

enter image description here

The UserControl relevant section is here:

<Grid x:Name="LayoutParent" >
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="12" />
        </Grid.RowDefinitions>

        <!-- I comment this if adding player dynamically -->
        <!--<wpf:VlcPlayer Grid.Row="0" x:Name="Player" />-->

        <!-- I un-comment this if adding player dynamically -->
        <Grid x:Name="VideoPlayerPanel" Grid.Row="0" Margin="0" />

        <StackPanel Grid.Row="1" Opacity="0.8">
            ...(buttons etc)
        </StackPanel>

        <ProgressBar ...(progressBar etc) />
</Grid>

My codebehind looks like this:

Dim Player As VlcPlayer = New VlcPlayer ' uncomment If adding the player dynamically

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Player.SetValue(Canvas.ZIndexProperty, -1)
        VideoPlayerPanel.Children.Add(Player)

        VolumeSlider.Value = 50
    End Sub

I have tried VerticalAlignment="Center" and VerticalAlignment="Stretch" in XAML on the VideoPlayerPanel, with Center the video disappears entirely, with Stretch it still aligns to the top.

Any thoughts as to what I might do to align this centrally would be much appreciated!

Upvotes: 0

Views: 184

Answers (3)

TripleAntigen
TripleAntigen

Reputation: 2299

Thanks to all that replied.

I did some more research, I substituted in a Rectangle for the player control and it aligned perfectly. That led me to discover that the third party control was itself at fault. I had to get the source and change the VerticalAlignment directly.

Sorry for the runaround.

Upvotes: 1

Nikolay
Nikolay

Reputation: 3828

When adding Player dynamiccaly you have different result, because you wrap Play in additional Grid. Try to add Player directly to first row of LayoutParent:

Player.SetValue(Grid.Row, 0)
LayoutParent.Children.Add(Player)

Upvotes: 1

AnjumSKhan
AnjumSKhan

Reputation: 9827

Remove Height="*" from first Row . * is used to occupy remaining space, so it is good to use it for the last Row.

Use fixed width and or Auto.

Upvotes: 0

Related Questions