问题
我有一个WPF工具包
DataGrid
,我想能够在几个预设的列顺序之间切换。这是一个MVVM项目,因此列顺序存储在
ViewModel
. 问题是,我无法让绑定为
DisplayIndex
财产。不管我怎么尝试,包括
this Josh Smith tutorial
我得到:
标题为“id”的DataGridColumn的DisplayIndex超出范围。DisplayIndex必须大于或等于0且小于Columns.Count。参数名称:DisplayIndex。实际值为-1。
有什么解决办法吗?
我在下面包含我的测试代码。如果你看到它有什么问题,请告诉我。
视图模型代码
public class MainViewModel
{
public List<Plan> Plans { get; set; }
public int IdDisplayIndex { get; set; }
public int NameDisplayIndex { get; set; }
public int DescriptionDisplayIndex { get; set; }
public MainViewModel()
{
Initialize();
}
private void Initialize()
{
IdDisplayIndex = 1;
NameDisplayIndex = 2;
DescriptionDisplayIndex = 0;
Plans = new List<Plan>
{
new Plan { Id = 1, Name = "Primary", Description = "Likely to work." },
new Plan { Id = 2, Name = "Plan B", Description = "Backup plan." },
new Plan { Id = 3, Name = "Plan C", Description = "Last resort." }
};
}
}
计划类
public class Plan
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
窗口代码
-此用途
Josh Smith's DataContextSpy
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:mwc="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Main Window" Height="300" Width="300">
<Grid>
<mwc:DataGrid ItemsSource="{Binding Plans}" AutoGenerateColumns="False">
<mwc:DataGrid.Resources>
<local:DataContextSpy x:Key="spy" />
</mwc:DataGrid.Resources>
<mwc:DataGrid.Columns>
<mwc:DataGridTextColumn
Header="ID"
Binding="{Binding Id}"
DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.IdDisplayIndex}" />
<mwc:DataGridTextColumn
Header="Name"
Binding="{Binding Name}"
DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.NameDisplayIndex}" />
<mwc:DataGridTextColumn
Header="Description"
Binding="{Binding Description}"
DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.DescriptionDisplayIndex}" />
</mwc:DataGrid.Columns>
</mwc:DataGrid>
</Grid>
</Window>
注:
如果我只是用普通数字
显示索引
,一切正常,所以问题肯定是绑定的问题。
5/1/2010更新
我只是对我的项目做了一点维护,当我运行它时,我在这篇文章中讨论的问题又回来了。我知道上次运行它时它是有效的,所以我最终把问题缩小到安装了较新版本的WPF工具包(2月10日)这一事实上。当我恢复到2009年6月的版本时,一切又恢复了正常。所以,我现在正在做我应该首先做的事情:我将wpftoolkit.dll包含在我的解决方案文件夹中,并将其签入版本控制。然而,不幸的是,新的工具箱有了一个突破性的变化。