2012-01-28 83 views
2

我有一個關於.NET 4.0中的標準WPF DataGrid的問題。以編程方式設置DataGrid行高度屬性

當我嘗試設置DataGrid中網格行高度programmaticaly使用簡單的代碼:

private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e) 
{ 
    e.Row.Height = 120;    
} 

一切順利,直到我嘗試調整使用鼠標一樣在Excel中的用戶界面/標準的側路網格行/ - 然後它出現網格行不能調整大小。它只是保持120.其內容的方式一切都搞砸了...

像Sinead O'Connor會說:告訴我寶貝 - 我哪裏出錯了?

回答

3

您不打算設置行本身的高度,因爲它通過標題等進行了調整。有一個屬性,DataGrid.RowHeight,它可以讓你做到這一點。

如果您需要設置高度選擇性,你可以創建一個風格和DataGridCellsPresenter的高度綁定到一些財產上的物品:

<DataGrid.Resources> 
    <Style TargetType="DataGridCellsPresenter"> 
     <Setter Property="Height" Value="{Binding RowHeight}" /> 
    </Style> 
</DataGrid.Resources> 

或者你可以從可視化樹主持人(我不要提倡這種做法),並指定一個高度有:

// In LoadingRow the presenter will not be there yet. 
e.Row.Loaded += (s, _) => 
    { 
     var cellsPresenter = e.Row.FindChildOfType<DataGridCellsPresenter>(); 
     cellsPresenter.Height = 120; 
    }; 

哪裏FindChildOfType是可以這樣來定義的擴展方法:

public static T FindChildOfType<T>(this DependencyObject dpo) where T : DependencyObject 
{ 
    int cCount = VisualTreeHelper.GetChildrenCount(dpo); 
    for (int i = 0; i < cCount; i++) 
    { 
     var child = VisualTreeHelper.GetChild(dpo, i); 
     if (child.GetType() == typeof(T)) 
     { 
      return child as T; 
     } 
     else 
     { 
      var subChild = child.FindChildOfType<T>(); 
      if (subChild != null) return subChild; 
     } 
    } 
    return null; 
} 
+0

謝謝閣下。解決問題:) – MegaMilivoje 2012-02-04 18:16:47

1

這對我有用。

private void SetRowHeight(double height) 
{ 
    Style style = new Style(); 
    style.Setters.Add(new Setter(property: FrameworkElement.HeightProperty, value: height)); 
    this.RowStyle = style; 
} 
相關問題