1

我想更改 DataGrid 的列宽,但一直收到错误消息。

这就是我填写 DataGrid 的方式:

tabel.ItemsSource = Item.getItemByCategory(category).DefaultView;

getItemByCategoryItem是返回 a 的类的静态方法DataTable

这就是我尝试调整列大小的方式:

tabel.Columns[1].Width = 100;

这是我收到的错误:

指数超出范围。必须是非负数且小于集合的大小。参数名称:索引

出于某种原因,tabel.Columns.Count == 0. 尽管在显示后立即显示了 4 列。

我可以在调整列大小方面获得一些帮助吗?

4

2 回答 2

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; }
    }


}
于 2012-07-15T11:54:33.483 回答
0

如果列是自动生成的,您应该推迟访问直到AutoGeneratedColumns触发。

于 2012-07-15T11:50:23.837 回答