2015-07-02 65 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

工作完美,谢谢! –