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

时间:2013-07-05 18:12:52

标签: c# wpf

我想在DataGrid中显示不同的表。我不想为每个表创建一个DataGrid。所以我必须从代​​码中动态添加DataGrid的ItemsSource。 如何在C#代码中实现此(WPF)ItemsSource="{Binding}"

1 个答案:

答案 0 :(得分:1)

将数据绑定设置为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>

设置datacontext(我更喜欢在Xaml中进行,但这比我想做的更多)...

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

在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;
}

现在你要做的就是将CurrentTable属性设置为你想要的任何表,它将更新UI并显示它。