简体   繁体   中英

Programmatically add binding to ItemsSource of DataGrid

I want to display different tables in a DataGrid. I don't want to create a DataGrid for each table. So I have to dynamically add the ItemsSource of the DataGrid from the code. How can I achieve this (WPF) ItemsSource="{Binding}" in the C# code.

Set the databinding to the property on your ViewModel that you want to bind to...

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:this ="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <DataGrid ItemsSource="{Binding CurrentTable}"/>
</Window>

Set the datacontext (I prefer to do it in Xaml, but that's more than I like to do for an example)...

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

Create the property on you ViewModel...

public class MainWindowViewModel : INotifyPropertyChanged
{
    private DataTable currentTable;

    public DataTable CurrentTable
    {
        get
        {
            return this.currentTable;
        }
        set
        {
            this.currentTable = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("CurrentTable"));
        }
    }

    public MainWindowViewModel()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Column1");
        table.Columns.Add("Column2");
        table.Rows.Add("This is column1", "this is column2");

        CurrentTable = table;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

All you have to do now is set the CurrentTable property to whatever table you want and it will update the UI and display it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM