2014-05-02 46 views
0

我有一個wpf應用程序,我在其中使用wpf網格併爲其動態添加/刪除控件。添加控件是好的,但是在刪除它們後,它們會從網格中消失,但是會留下空白的地方,這些空間會被其餘元素佔據,就像它們在包裝面板中一樣。在運行時刪除元素時刷新WPF網格佈局

此前我使用包裝面板,它工作正常,但我需要在我的groupboxes中添加分隔控制,因此我用網格替換了wrappanel。

下面是窗口的截圖

enter image description here

我取出中間組合框中並顯示這樣

enter image description here

我想要的第三組框佔據第二的位置組框。 對於記錄,我已經使用網格調整大小事件,這是它具有

foreach (var control in this.DynamicGrid.Children) 
     { 
      if (control.GetType() == typeof(GroupBox)) 
      { 
       GroupBox groupBox = control as GroupBox; 
       groupBox.Height = this.DynamicGrid.ActualHeight; 
       this.WrapPanel1.Width = this.DynamicGrid.ActualWidth; 
      } 
     } 

Wrappanel具有其中我們添加/刪除元素動態網格的代碼。

回答

0

您可以設置 <ColumnDefinition width="Auto" />

,並使用 Visibility="Collapsed"隱藏的列。

+0

ColumnDefinition寬度=「自動」解決了這個問題對我來說。 – MegaMind

+0

好:)只是要小心,你仍然可以使用標籤來關注隱藏的控件。如果你有一些鍵盤操作,你應該做一些事情來防止它。 –

+0

如果我使用Column definition =「Auto」,但網格沒有調整自身大小,元素會對齊。它也應該減小其寬度。 – MegaMind

0

我看不到你的問題......好像你在問'如何在代碼中使用Grid控件?'。如果您想在運行時更改Grid.ColumnDefinitions(或任何其他Grid屬性),那麼爲什麼不這樣做呢?如果您查看MSDN上的Grid Class頁面,您會看到一個長代碼示例,它將向您顯示如何在代碼中操作Grid。例如,你可以做這樣的事情:

ColumnDefinition rightHandColumn = new ColumnDefinition(); 
YourGrid.ColumnDefinitions.Add(rightHandColumn); 
YourGrid.Children.Add(uiElementCurrentlyInGrid); 
YourGrid.SetRow(uiElementCurrentlyInGrid, 0); 
YourGrid.SetColumn(uiElementCurrentlyInGrid, 1); 

然後刪除一個項目:

Grid.Children.Remove(uiElementCurrentlyInGrid); 
Grid.ColumnDefinitions.Remove(rightHandColumn);