所以我读了一个XML文件,然后将数据显示在DataGrid上。一旦我将XML文件的DataView绑定到datagrid的ItemsSource,我就会尝试隐藏将要创建的第4列(它是我不想显示的ID)但是收到错误
System.Windows.Markup.XamlParseException
HResult=0x80131501
Message='The invocation of the constructor on type 'MoneyLog.MainWindow' that matches the specified binding constraints threw an exception.' Line number '6' and line position '9'.
Source=PresentationFramework
StackTrace:
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
Inner Exception 1:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
我使用的代码:
DataGrid.Columns[4].Visibility = Visibility.Collapsed;
从错误中我可以看出,显然我的数字(4)超出范围,因此我认为该表必须尚未创建。为了解决这个问题,我编写了一个粗略的黑客,将代码块延迟了半秒,这解决了问题......?
DataGrid.ItemsSource = dataView;
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
timer.Start();
timer.Tick += (sender, args) =>
{
timer.Stop();
DataGrid.Columns[3].Width = 250;
DataGrid.Columns[4].Visibility = Visibility.Collapsed;
DataGrid.CanUserAddRows = false;
DataGrid.IsReadOnly = true;
};
我的问题是,如果没有这个完整的计时器解决方法,还有另一种方法吗?