简体   繁体   English

以编程方式将绑定添加到DataGrid的ItemsSource

[英]Programmatically add binding to ItemsSource of DataGrid

I want to display different tables in a DataGrid. 我想在DataGrid中显示不同的表。 I don't want to create a DataGrid for each table. 我不想为每个表创建一个DataGrid。 So I have to dynamically add the ItemsSource of the DataGrid from the code. 因此,我必须从代​​码中动态添加DataGrid的ItemsSource。 How can I achieve this (WPF) ItemsSource="{Binding}" in the C# code. 如何在C#代码中实现此(WPF) ItemsSource="{Binding}"

Set the databinding to the property on your ViewModel that you want to bind to... 将数据绑定设置为要绑定到的ViewModel属性。

<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)... 设置数据上下文(我更喜欢在Xaml中进行操作,但这比我举个例子要多)...

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

Create the property on you ViewModel... 在您的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. 现在您要做的就是将CurrentTable属性设置为所需的任何表,它将更新UI并显示它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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