WPF绑定数据源

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<TestDataItem> list = new ObservableCollection<TestDataItem>();

public MainWindow()
{
InitializeComponent();

for (int i = 0; i < 20; i++)
{
list.Add(new TestDataItem() { Id = Guid.NewGuid()});
}
this.DataContext = list;
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
ObservableCollection<TestDataItem> temp = this.DataContext as ObservableCollection<TestDataItem>;
if (temp != null && temp.Count > 0)
{
temp.Add(new TestDataItem() { Id = Guid.NewGuid() });
}
}
}
public class TestDataItem:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private Guid id = Guid.NewGuid();
public Guid Id
{
get { return Guid.NewGuid(); }
set
{
this.id = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Id"));
}
}
}
}
}

______________________________________

<Window xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Vertical">
<Button Click="Button_Click_1" Width="30" Height="30" Content="OK"/>
<dxg:GridControl x:Name="grid" Height="500" ItemsSource="{Binding}">
<dxg:GridControl.Columns>
<dxg:GridColumn FieldName="Id" />
</dxg:GridControl.Columns>
<dxg:GridControl.View>
<dxg:TableView x:Name="view" AutoWidth="True" />
</dxg:GridControl.View>
</dxg:GridControl>
</StackPanel>
</Grid>
</Window>

原文地址:https://www.cnblogs.com/binbinxiong/p/3793851.html