我在 WPF 应用程序中有一个 ViewModel 和一个 View。屏幕上有一系列输入(日期选择器、文本框和组合框)。
输入绑定到 ViewModel 的 NewItem 属性,DataGrid 绑定到 WorkLog 集合属性。
当用户单击“添加”按钮时,我希望将 NewItem 添加到 WorkLog 集合中,并重置 NewItem 属性以允许用户添加更多项目。问题是,当我添加项目时,如果我重新实例化 NewItem,那么控件仍然会被填充,但在后台 VM 值都是默认值(或空值),因此它不起作用。
如何重置 NewItem 属性并更新 UI 以反映这一点?我尝试 INotifyPropertyChanged 无济于事(因为我正在设置新实例而不是更改值)。
为了简洁起见,我已经修剪了代码
模型
public class WorkLogItem : INotifyPropertyChanged
{
public WorkLogItem()
{
this.Datestamp = DateTime.Today;
this.Staff = new Lookup();
this.WorkItem = new Lookup();
}
#region ID
private Int32 _ID;
public Int32 ID
{
get { return this._ID; }
set
{
this._ID = value;
FirePropertyChanged("ID");
}
}
#endregion
#region Datestamp
private DateTime? _Datestamp;
public DateTime? Datestamp
{
get { return this._Datestamp; }
set
{
this._Datestamp = value;
FirePropertyChanged("Datestamp");
}
}
#endregion
#region Staff
private Model.Lookup _Staff;
public Model.Lookup Staff
{
get { return this._Staff; }
set
{
this._Staff = value;
FirePropertyChanged("Staff");
}
}
#endregion
#region WorkItem
private Model.Lookup _WorkItem;
public Model.Lookup WorkItem
{
get { return this._WorkItem; }
set
{
this._WorkItem = value;
FirePropertyChanged("WorkItem");
}
}
#endregion
#region Hours
private Decimal _Hours;
public Decimal Hours
{
get { return this._Hours; }
set
{
this._Hours = value;
FirePropertyChanged("Hours");
}
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void FirePropertyChanged(String name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
}
查看模型
public Model.WorkLogItem NewItem { get; set; }
public ObservableCollection<Model.WorkLogItem> WorkLog { get; set; }
看法
<Label Content="Date " />
<DatePicker SelectedDate="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.NewItem.Datestamp, NotifyOnSourceUpdated=True}" />
<Label Content="Work Item " />
<ComboBox Grid.Column="1" Grid.Row="2" DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.WorkItems}" ItemsSource="{Binding}" DisplayMemberPath="Value" SelectedValuePath="ID" SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.WorkLogItem.Type, NotifyOnSourceUpdated=True}" IsSynchronizedWithCurrentItem="True" />
<Label Grid.Row="3" Content="Hours " />
<TextBox Grid.Column="1" Grid.Row="3" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.NewItem.Hours, NotifyOnSourceUpdated=True}" />
C#
在 Window_Loaded 中:
this.DataContext = this.VM;
在 Add_Click
this.VM.WorkLog.Add(this.VM.NewItem);
this.VM.NewItem = new Model.WorkLogItem();