如何从C#代码中扩展DataGrid列?
我在我的C#代码中创建了WPF DataGrid
的列。 我希望其中一列自动拉伸到DataGrid
的宽度。 在XAML中,我设置Width="*"
。 我如何在代码中执行此操作?
编辑
一些答案似乎引导我找到正确的解决方案,但我觉得我需要详细说明我正在尝试做的事情:
我实际上是从DataGrid
派生出一个新类。 在它的构造函数中,我添加了四列:
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建议:
mdColumn.Width = new DataGridLength(0.5, DataGridLengthUnitType.Star);
但是这会创建一个如此宽的列,我可以滚动和滚动很长时间……当我使用0.1
甚至更小的值时,同样的问题。
我觉得在某种程度上,我在错误的地方做这件事?
编辑2
好吧,我可能有问题,因为我实际上是将它添加到ScrollViewer
。 我先做一些进一步的测试……
编辑3
好吧,当在ScrollViewer
中使用DataGrid
时,事情不起作用……当我删除ScrollViewer
,就像user24601说的那样。
你实际上在那里使用了一个名为DataGridLength的东西。
尝试这样的事情:
Grid.ColumnDefinitions[0].Width = new DataGridLength(0.2, DataGridLengthUnitType.Star); Grid.ColumnDefinitions[1].Width = new DataGridLength(0.8, DataGridLengthUnitType.Star);
这将把这两列之间的剩余空间分成80%/ 20%。
试试这个
DataGrid1.Width = double.NaN;
上述就是C#学习教程:如何从C#代码中扩展DataGrid列?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1000738.html