[英]Programmatically add binding to ItemsSource of DataGrid
我想在DataGrid中显示不同的表。 我不想为每个表创建一个DataGrid。 因此,我必须从代码中动态添加DataGrid的ItemsSource。 如何在C#代码中实现此(WPF) ItemsSource="{Binding}"
。
将数据绑定设置为要绑定到的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>
设置数据上下文(我更喜欢在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并显示它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.