我的model:
public class Column { public int Id { get; set; } public int TableId { get; set; } public string Name { get; set; } public int MaxLength { get; set; } public string Comment { get; set; } public bool IsNullable { get; set; } }
ViewModel:
public class ColumnViewModel : ViewModelBase { #region members private Column _field; #endregion #region constructors public ColumnViewModel(Column field) { _field = field; } #endregion #region PropertyNames
public string MaxLengthPropertyName = "MaxLength";
public string CommentPropertyName = "Comment";
public string IsNullablePropertyName = "IsNullable";
#endregion #region public Properties public int Id { get { return _field.Id; } } public int TableId { get { return _field.TableId; } } public string Name { get { return _field.Name; } } public int MaxLength { get { return _field.MaxLength; } set { if (_field.MaxLength == value) return; _field.MaxLength = value; RaisePropertyChanged(MaxLengthPropertyName); } } public string Comment { get { return _field.Comment; } set { if (_field.Comment == value) return; _field.Comment = value; RaisePropertyChanged(CommentPropertyName); } } public bool IsNullable { get { return _field.IsNullable; } set { if (_field.IsNullable == value) return; _field.IsNullable = value; RaisePropertyChanged(IsNullablePropertyName); } } #endregion
View代码:
<DataGrid Name="DgrdColumns" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="150"></DataGridTextColumn> <DataGridTemplateColumn Header="MaximumLength"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding MaxLength, Mode=TwoWay}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Comment" Width="150"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding Comment, , Mode=TwoWay}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
View后台数据绑定代码:
void BindData() { #region datas _columns = new List<Column> { new Column() { Id = 1, TableId = 2, Name = "first", Comment = "first comment", IsNullable = true }, new Column() { Id = 2, TableId = 2, Name = "second", Comment = "second comment", IsNullable = true }, new Column() { Id = 3, TableId = 2, Name = "third", Comment = "third comment", IsNullable = false } }; #endregion viewModels = new ObservableCollection<ColumnViewModel>(_columns.Select(x => new ColumnViewModel(x))); DgrdColumns.ItemsSource = viewModels; }
当我在后台改动Model的值时,View显示确实变了
但是当我改变View时, 后台Model的值却没有变化