1

.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 中的外观相对应的列宽?

4

1 回答 1

0

为你解决你的问题必须通过这个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);
                }

而不是使用TextBlockI used DataGridColumnHeader,它具有ContextMenu属性,因此占用了Header.

于 2015-07-02T20:27:50.313 回答