这是一个非常简单的例子:
<Window x:Class="DataGridUpdateSourceTriggerOneWay.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridUpdateSourceTriggerOneWay"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="DataGrid1"
IsReadOnly="False"
AutoGenerateColumns="False"
CanUserAddRows="False"
ItemsSource="{Binding data}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Field">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Name, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Length of Field">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Length, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Width="Auto"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
这是你的DataGrid,它的ItemsSource一定到存在于数据后面的代码隐藏:
public partial class MainWindow : Window
{
public ObservableCollection<Data> data { get; set; }
public MainWindow()
{
InitializeComponent();
data = new ObservableCollection<Data>();
data.Add(new Data() { Name = "Data1", Length = 1 });
data.Add(new Data() { Name = "Data2", Length = 2 });
this.DataContext = this;
}
}
集合需要通知其绑定视图元素的内容已经改变(项目添加或删除),这就是ObservableCollection<Data>
的工作。
这里是数据类:
public class Data : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
private int _Length;
public int Length
{
get { return _Length; }
set
{
_Length = value;
PropertyChanged(this, new PropertyChangedEventArgs("Length"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
的INotifyPropertyChanged
接口是为特定目的的观察者模式的实现部分:通知用户是在发布一个属性的值刚刚改变。因此,更改这两个propeties,存在集合的实例的名称或长度将导致View更新。
让我知道你是否需要更多细节。
哦,我忘了,你会如何添加一个新的行?只需处理放置在视图某处的Button的Click事件,并将新的Data实例添加到数据收集中即可。
例:
data.Add(new Data() { Name = "Data3", Length = 3 });
假设你正在使用MVVM和数据绑定...添加行,绑定你'DataGrid'在视图模型的'的ObservableCollection',然后就添加/删除集合中的项目。它们会反映在'DataGrid'中。 –
@GrantWinney你能给我一个示例代码吗? –