[英]How to change the width of column in datagrid in wpf
看來這是一個簡單的問題,但不知何故我找不到正確的答案。 我在wpf中有datagrid,我想在其中更改c#中列的寬度。 該代碼是
DataTable table = new DataTable();
DataColumn col1 = new DataColumn("From", typeof(string));
table.Columns.Add(col1);
table.Columns.Add(new DataColumn("To", typeof(string)));
table.Columns.Add(new DataColumn("Occurrence", typeof(int)));
dataGrid1.ItemsSource = table.DefaultView;
但是DataColumn沒有寬度選項。 在這種情況下如何更改列的寬度? 謝謝。
DataColumn僅用於數據,不是WPF對象,這就是為什么它沒有寬度的原因。
您可以在dataGrid1的列上設置寬度
dataGrid1.Columns[0].Width = 50;
...但是,如果您將AutoGenerateColumns設置為true,則可能無法正常工作,此外,C#代碼樣式也不是一種好習慣。
完全控制的最佳方法是使用XAML並將每一列綁定到數據網格。 該站點對數據網格和綁定提供了很好的指南http://www.wpftutorial.net/datagrid.html
我找到正確的解決方案。 只需添加
dataGrid1.ColumnWidth = 100;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.