【问题标题】:Why doesn't Generate Columns work for a DataGrid bound to the DataView of a DataTable?为什么生成列不适用于绑定到 DataTable 的 DataView 的 DataGrid?
【发布时间】:2012-06-26 19:46:27
【问题描述】:

我对类型化 DataTable 的 DataView 属性有一个 DataGrid,但是当我单击生成列时,我得到“您必须先设置 ItemsSource,然后才能执行此操作”。不知道我在这里做错了什么。请参阅下面的 XAML:

    <DataGrid AutoGenerateColumns="True" HorizontalAlignment="Stretch" 
      Margin="0" Name="dataGrid1" VerticalAlignment="Stretch" 
      ItemsSource="{Binding Path=DataView/}" 
      DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:MainWindow, AncestorLevel=1},
      Path=TransferSchedulesView/}">

TransferSchedulesView 是我的 MainWindow 上的一个属性,它公开了类型化 DataTable 成员的 DataView 属性。关于我在哪里出错的任何建议?

【问题讨论】:

  • 在设计模式下会发生吗?
  • 是的,在 DataGrid 的属性窗口中,有“生成列”和“编辑实体绑定列”链接按钮。单击其中任何一个时都会出现错误
  • 运行时发生了什么?
  • 我得到一个没有列的空 DataGrid
  • 输出窗口仍然没有绑定错误?

标签: wpf xaml datagrid


【解决方案1】:

我看到你的绑定可能不正确。从绑定中删除前导斜杠,因为您绑定的不是集合,所以它没有当前项。

这是我在尝试您的示例时在输出中看到的内容:

System.Windows.Data 错误:40:BindingExpression 路径错误:'' 在“当前收藏品”中找不到属性 ''TransferSchedulesView' (HashCode=19117974)'。 BindingExpression:Path=TransferSchedulesView/;数据项='主窗口' (名称='');目标元素是'DataGrid'(名称='dataGrid1');目标 属性是“DataContext”(类型“对象”)

这是我的工作示例。如果你运行它,你会看到自动生成的列:

<DataGrid AutoGenerateColumns="True"
    ItemsSource="{Binding Path=DataView}" 
    DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=WpfApplication1:MainWindow, AncestorLevel=1}, Path=TransferSchedulesView}" />

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public TransferSchedulesView TransferSchedulesView { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            TransferSchedulesView = new TransferSchedulesView(){DataView = CreateTable()};
        }

        private static DataTable CreateTable()
        {
            var dataTable = new DataTable();
            dataTable.Columns.Add("aaa");
            dataTable.Columns.Add("bbb");
            dataTable.Columns.Add("ccc");
            dataTable.Rows.Add("sdaasdasd", "dsdsadasdasdsd", "sdasdadsadsadsd");
            dataTable.Rows.Add("sdaasdasd", "dsdsadasdasdsd", "sdasdadsadsadsd");
            dataTable.Rows.Add("sdaasdasd", "dsdsadasdasdsd", "sdasdadsadsadsd");
            return dataTable;
        }
    }

    public class TransferSchedulesView
    {
        public DataTable DataView { get; set; } 
    }
}

【讨论】:

  • 完美,这行得通。另一个问题是,如果表中没有数据,您将无法获得列信息
猜你喜欢
  • 2016-02-24
  • 2010-10-04
  • 1970-01-01
  • 2011-07-26
  • 2011-04-09
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多