WPF DataGrid binding to DataTable in XAML

bindingdatagriddatatablewpfxaml

I'm completely new to WPF/XAML. I'm trying to work out XAML code to bind a DataTable to DataGrid. What I have is an instance of custom DataContainer class which implements INotifyPropertyChanged. This class has a property:

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

now, in the C'tor of my MainWindow I have this, which works like a charm:

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

How do I make this binding in XAML?

Best Answer

You need to use an 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-->

Then you can bind it to your datagrid in XAML with

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

There are different ways to do bindings in xaml though, so play around with it a bit.

Related Topic