2015-07-02 61 views
1

.NET4.0:我在代碼隱藏中構建DataGrid,所以我沒有使用任何XAML。僅限C#。當用戶右鍵單擊列標題中的任何位置時,我想顯示一個上下文菜單。下面是一些代碼給你一個想法:WPF - DataGridColumn寬度不返回預期值

public void MakeAllColumns() 
    { 
     for (int i = 0; i < AllColumnDisplayNames.Length; i++) 
     { 
      // create a new column depending on the data to be displayed 
      DataGridTextColumn col = new DataGridTextColumn(); 
      col.MaxWidth = 300; 

      // create a new Textblock for column's header and add it to the column 
      TextBlock headerText = new TextBlock() { Text = AllColumnDisplayNames[i] }; 
      col.Header = headerText; 

      /// create a new context menu and add it to the header 
      ContextMenu menu = new ContextMenu(); 
      headerText.ContextMenu = menu; 

      // build the context menu depending on the property 
      menu.Items.Add(new Button() { Content = "FOOBAR" }); 

      // add the bindings to the data 
      col.Binding = new Binding(AllColumnBindings[i]); 

      AllColumns.Add(AllColumnDisplayNames[i], col); 
     } 
    } 

這種方法的問題是,用戶需要點擊文本框實際,以激活上下文菜單,而不是在標題的任何地方。

因爲我想不出讓TextBox填充頁眉寬度的方法,我所能做的就是將TextBox寬度屬性更改爲綁定到列寬。這些列伸展以適合他們的內容,因此它們具有不同的寬度。但是,當我將所有列的ActualWidth屬性打印到控制檯時,它表示它們都具有寬度20,這不像我的GUI看起來那樣。我如何獲得與我的GUI中的外觀相對應的列寬?

回答

0

爲您解決問題,必須通過該機構交換Ø你的身體的方法:

此代碼進行了測試:

for (int i = 0; i < AllColumnDisplayNames.Length; i++) 
       { 
        // create a new column depending on the data to be displayed 
        DataGridTextColumn col = new DataGridTextColumn(); 
        col.MaxWidth = 300; 

        /// create a new context menu 
        ContextMenu menu = new ContextMenu(); 

        // build the context menu depending on the property 
        menu.Items.Add(new Button() { Content = "FOOBAR" }); 

        // create a new column's header and add it to the column 
        DataGridColumnHeader head = new DataGridColumnHeader() { Content = AllColumnBindings[i] }; 
        head.ContextMenu = menu;//add context menu to DataGridColumnHeader 
        col.Header = head; 

        // add the bindings to the data 
        col.Binding = new Binding(AllColumnBindings[i]); 

        AllColumns.Add(AllColumnDisplayNames[i], col); 
       } 

而不是使用TextBlock我用DataGridColumnHeader,它具有ContextMenu財產,從而佔據了Header的所有空間(高度和寬度)。

+0

工作完美,謝謝! –