如何使C#代码扩展DataGrid列? [英] How to make DataGrid column stretch from C# code?
问题描述
我正在用C#代码创建WPF DataGrid
的列。我希望其中一列自动扩展到 DataGrid
的宽度。在XAML中,我将设置 Width = *
。我该如何在代码中做到这一点?
I'm creating the columns of a WPF DataGrid
in my C# code. I want one of the columns to stretch to the width of the DataGrid
automatically. In XAML, I'd set Width="*"
. How do I do it in code?
编辑
有些答案似乎使我找到了正确的解决方案,但我觉得我需要详细说明一下:
EDIT
Some of the answers seem to lead me to the right solution, but I feel I need to elaborate a bit more what I'm trying to do:
我实际上是从 DataGrid派生一个新类的
。在其构造函数中,我添加了四列,例如:
I'm actually deriving a new class from DataGrid
. In its constructor, I add four columns like that:
this.IsReadOnly = true;
this.AutoGenerateColumns = false;
this.ItemsSource = m_dataSource;
DataGridTextColumn anColumn = new DataGridTextColumn() { Header = "Col1", Binding = new Binding("B1") };
DataGridTextColumn tpColumn = new DataGridTextColumn() { Header = "Col2", Binding = new Binding("B2") };
DataGridTextColumn txColumn = new DataGridTextColumn() { Header = "Col3", Binding = new Binding("B3") };
DataGridTextColumn mdColumn = new DataGridTextColumn() { Header = "Col4", Binding = new Binding("B4") };
this.Columns.Add(anColumn);
this.Columns.Add(tpColumn);
this.Columns.Add(txColumn);
this.Columns.Add(mdColumn);
我尝试设置最后一列的宽度,如 user24601 建议:
I tried setting the last column's width like user24601 suggested:
mdColumn.Width = new DataGridLength(0.5, DataGridLengthUnitType.Star);
但这会创建一个如此宽的列,我可以滚动并滚动 very 很长时间...当我使用 0.1
或更小的值时,同样的问题。
But this creates a column that is so wide I can scroll and scroll for a very long time... Same problem when I use 0.1
or even smaller values.
我似乎我是在错误的地方做的吗?
I seems to me I'm doing it in the wrong place somehow?
编辑2
好吧,我可能有问题因为我实际上是将它添加到 ScrollViewer
中。我将首先运行一些进一步的测试...
EDIT 2
OK, I may have the problem because I'm actually adding this to a ScrollViewer
. I'll run some further tests first...
编辑3
在 ScrollViewer
中包含 DataGrid
...当我删除 ScrollViewer $ c时$ c>,事情就像 user24601 所说的那样工作。
EDIT 3
Well, things don't work when having the DataGrid
within a ScrollViewer
... When I remove the ScrollViewer
, things work like user24601 said.
推荐答案
您实际上正在使用一种称为在那里 DataGridLength 。
You're actually using something called a DataGridLength there.
尝试类似这样的事情:
Grid.ColumnDefinitions[0].Width = new DataGridLength(0.2, DataGridLengthUnitType.Star);
Grid.ColumnDefinitions[1].Width = new DataGridLength(0.8, DataGridLengthUnitType.Star);
这将在这两列之间分配80%/ 20%的剩余空间。
That will split the remaining space 80% / 20% between these two columns.
这篇关于如何使C#代码扩展DataGrid列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!