【问题标题】:WPF - DataGridColumn Width not Returning Expected ValueWPF - DataGridColumn 宽度不返回预期值
【发布时间】:2015-09-20 01:47:30
【问题描述】:

.NET4.0:我正在代码隐藏中构建一个 DataGrid,所以我没有使用任何 XAML。仅限 C#。当用户右键单击列标题中的任意位置时,我想显示一个上下文菜单。这里有一些代码可以给你一个想法:

    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 填充标题宽度的方法,所以我所能做的就是更改 TextBox 宽度属性以绑定到列的宽度。列拉伸以适应其内容,因此它们具有不同的宽度。但是,当我将所有列 ActualWidth 属性打印到控制台时,它说它们的宽度都是 20,这不是我的 GUI 的样子。如何获得与其在我的 GUI 中的外观相对应的列宽?

【问题讨论】:

    标签: c# wpf wpfdatagrid datagridcolumn datagridcolumnheader


    【解决方案1】:

    为了你解决你的问题必须通过这个body来交换你的body方法:

    此代码已经过测试:

    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的所有空间(高度和宽度)。

    【讨论】:

      猜你喜欢
      • 2012-03-21
      • 2013-03-22
      • 2012-02-04
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多