簡體   English   中英

WPF-DataGridColumn寬度不返回期望值

[英]WPF - DataGridColumn Width not Returning Expected Value

.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 width屬性以綁定到列的寬度。 列會拉伸以適合其內容,因此它們具有不同的寬度。 但是,當我將所有列的ActualWidth屬性打印到控制台時,它表示它們的寬度均為20,這與我的GUI外觀不同。 如何獲得與其在GUI中的外觀相對應的列寬?

為了解決您的問題,必須通過該身體來交換您的身體方法:

此代碼已經過測試:

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而是使用了具有ContextMenu屬性的DataGridColumnHeader ,因此占據了Header所有空間(高度和寬度)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM