【问题标题】:WPF DataGrid binding to DataTable in XAMLWPF DataGrid 绑定到 XAML 中的 DataTable
【发布时间】:2011-08-17 01:58:07
【问题描述】:

我对 WPF/XAML 完全陌生。我正在尝试制定 XAML 代码以将 DataTable 绑定到 DataGrid。我拥有的是实现 INotifyPropertyChanged 的​​自定义 DataContainer 类的实例。这个类有一个属性:

private DataTable totalsStatus = new DataTable();
public DataTable TotalsStatus
{
    get { return totalsStatus; }
    set
    {
        totalsStatus = value;
        NotifyPropertyChanged("TotalsStatus");
    }
}

现在,在我的 MainWindow 的 C'tor 中,我有这个,它就像一个魅力:

Binding b = new Binding();
b.Source = DataContainer;
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.Path = new PropertyPath("TotalsStatus");
DataGridMain.SetBinding(DataGrid.ItemsSourceProperty, b);

如何在 XAML 中进行此绑定?

【问题讨论】:

  • 我试图从这个问题中找出如何解决我的问题:我在我的代码中尝试了这个,它与我的 DataGrid "_gridData.ItemsSource = ((DataTable) base.ItemsSource).DefaultView;"但是,您现在如何在 C#(无 XAML)中以编程方式绑定 DataGrid 列?

标签: wpf xaml datagrid binding datatable


【解决方案1】:

您需要使用objectdataprovider

<ObjectDataProvider x:Key="yourdataproviderclass" 
                    ObjectType="{x:Type local:yourdataproviderclass}" />

<ObjectDataProvider x:Key="dtable" 
                    ObjectInstance="{StaticResource yourdataproviderclass}"
                    MethodName="GetTable"/> <!--here would be the method that returns your datasource-->

然后您可以使用 XAML 将其绑定到您的数据网格

<DataGrid ItemsSource="{Binding Source={StaticResource dtable}}" ></DataGrid>

虽然在 xaml 中进行绑定有不同的方法,所以请尝试一下。

【讨论】:

  • 最后,我决定在 XAML 中实例化我的类,并在后面的代码中使用 FindResource() 实例化,这使所有代码更加简洁。
猜你喜欢
  • 2013-07-28
  • 2011-02-05
  • 2018-02-07
  • 2013-06-20
  • 2023-04-06
  • 1970-01-01
  • 2013-03-24
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多