【发布时间】:2011-01-08 17:39:24
【问题描述】:
问题
我有一个 WPF 工具包DataGrid,我希望能够在几个预设的列顺序之间切换。这是一个 MVVM 项目,因此列顺序存储在 ViewModel 中。问题是,我无法让绑定为DisplayIndex 属性工作。无论我尝试什么,包括this Josh Smith tutorial 中的甜蜜方法,我都得到:
标头为“ID”的 DataGridColumn 的 DisplayIndex 超出范围。 DisplayIndex 必须大于或等于 0 且小于 Columns.Count。参数名称:displayIndex。实际值为 -1。
有什么解决方法吗?
我在下面包含了我的测试代码。如果您发现任何问题,请告诉我。
ViewModel 代码
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>
注意:如果我只对DisplayIndex 使用纯数字,一切正常,所以问题肯定出在绑定上。
2010 年 5 月 1 日更新
我刚刚对我的项目进行了一些维护,我注意到当我运行它时,我在这篇文章中讨论的问题又回来了。我知道上次运行它时它可以工作,所以我最终将问题缩小到我安装了更新版本的 WPF Toolkit(2010 年 2 月)这一事实。当我恢复到 09 年 6 月的版本时,一切都恢复正常了。所以,我现在正在做我应该首先做的事情:我将 WPFToolkit.dll 包含在我的解决方案文件夹中,并将其检入到版本控制中。不过很遗憾,较新的工具包发生了重大变化。
【问题讨论】:
标签: wpf data-binding xaml mvvm wpftoolkit