2016-04-21 22 views
0

嗨我想我可以很容易地解決這個問題,但這讓我瘋狂。當動態添加WPF控件對齊方式是錯誤的

我正在使用UserControl來安裝基於VLC的視頻播放器控件,以及播放和停止按鈕等。然後將UserControl放置在我的主窗體上。如果UserControl在XAML中聲明,則表現正常。

我決定重寫代碼來動態實例化我的UserControl,以防我需要銷燬它並在運行中創建另一個。但是當我做視頻移動到它的容器的頂部而不是中間時。

enter image description 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> 

我隱藏看起來是這樣的:

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 

我試圖在XAML VerticalAlignment="Center"VerticalAlignment="Stretch"在VideoPlayerPanel,與中心視頻完全消失,Stretch仍然對齊頂部。

任何想法,我可能會做什麼來集中對齊將非常感激!

+1

我的猜測是,你把你的VLC UI放在Canvas上,這是一個必須明確聲明尺寸的控件。因此,例如,當您將控件放置在網格中時,框架無法計算正確的排列方式。請記住,Canvas始終大小爲零,除非您聲明寬度和高度。 –

+0

在代碼背後創建XAML的東西往往不是一個好主意。沒有太多的東西不是最好的模板。我花在XAML上的時間越多,看到的東西就越多,並想「爲什麼我會這樣做?」您是否遇到過一些常規性的問題? –

回答

0

從第一個刪除Height="*"*用於佔用剩餘空間,所以最好使用。

使用固定寬度和或者Auto

+0

在這種情況下,即使該空間佔據網格中的第一行,我也希望視頻適合填充下列行後留下的剩餘空間,所以*就是我想要的。 – TripleAntigen

1

當添加播放器動態播放時,您會得到不同的結果,因爲您將播放放在其他網格中。嘗試將播放器直接添加到LayoutParent的第一行:

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

我以前也曾嘗試過LayoutParent,結果也一樣。我試過Player.SetValue(Grid.Row,0)但是沒有編譯,我想因爲Grid.Row是一個附屬的屬性。 Grid.RowProperty是有效的,但沒有區別。 – TripleAntigen

+1

你可以爲你的UserConrol顯示XAML嗎?我無法用簡單的UserControl重現此問題,其中包含具有背景的固定高度網格 – Nikolay

1

感謝所有回覆。

我做了一些更多的研究,我用一個矩形代替了玩家控制,並且它完全對齊。這讓我發現第三方控制本身就是錯誤的。我必須獲取源代碼並直接更改VerticalAlignment。

對不起。