我想更改DataGrid的列宽,但我一直收到错误。
这就是我填写DataGrid的方式:
tabel.ItemsSource = Item.getItemByCategory(category).DefaultView;
getItemByCategory
是Item
类的静态方法,返回DataTable
。
这是我尝试调整列的大小:
tabel.Columns[1].Width = 100;
这是我收到的错误:
指数超出范围。必须是非负数且小于集合的大小。 参数名称:index
出于某种原因,tabel.Columns.Count == 0
。虽然在显示后立即显示4列。
我可以在调整列的大小方面获得一些帮助吗?
答案 0 :(得分:3)
尝试类似的东西:
XAML文件:
<Window x:Class="DataGridView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid Name="table" Loaded="table_Loaded" />
</Grid>
</Window>
代码隐藏文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
namespace DataGridView
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
table.ItemsSource = getItemByCategory().DefaultView;
}
public static DataTable getItemByCategory(int category = 0)
{
//ServiceReference.ServiceSoapClient instance = Database.getClient();
DataTable tabel = new DataTable();
DataRow linie;
tabel.Columns.Add(new DataColumn("id", typeof(int)));
tabel.Columns.Add(new DataColumn("name", typeof(string)));
//tabel.Columns.Add(new DataColumn("price", typeof(int)));
//tabel.Columns.Add(new DataColumn("inCart", typeof(bool)));
//ServiceReference.ArrayOfString[] values = instance.getItemsByCategory(category);
List<Foo> values = new List<Foo>();
for (int i = 0; i < 10; i++)
{
values.Add(new Foo { ID = i, Name = "name " + i });
}
foreach (var v in values)
{
linie = tabel.NewRow();
linie["id"] = v.ID;
linie["name"] = v.Name;
//linie["price"] = Convert.ToInt32(v[3]);
//linie["inCart"] = false;
tabel.Rows.Add(linie);
}
return tabel;
}
private void table_Loaded(object sender, RoutedEventArgs e)
{
table.Columns[0].Width = 100;
table.Columns[1].Width = 200;
}
}
public class Foo
{
public int ID { get; set; }
public string Name { get; set; }
}
}
答案 1 :(得分:0)
如果列是自动生成的,则应推迟访问,直到AutoGeneratedColumns
触发。