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