我有一个绑定(bind)到 viewmodel.SelectedDate 的 DatePicker 控件。我没有使用 propfull,而是使用 CTK [ObservableProperty]。当我选择一个新日期时,我想调用另一个函数,该函数根据该新日期获取新的数据集。还有其他注释吗?
/// Set by the Date Control on the form
[ObservableProperty]
//[AlsoCallThisFunction(DisplayBookings)]
public DateTime bookingDate;
///I want to call this for a fresh dataset
///after the bookingDate is set
void DisplayBookings()
{
GoToDatabaseAndGetNewRecordset(bookingDate);
}
旧的做法:
//private DateTime bookingDate;
//public DateTime BookingDate
//{
// get { return bookingDate; }
// set {
// bookingDate = value;
// DisplayBookings();
// }
//}
最佳答案
您可以重写 OnPropertyChanging
和 OnPropertyChanged
事件,并在那里调用您的方法。
请记住,如果您将绑定(bind)设置为 UpdateSourceTrigger=PropertyChanged
,则某些更改可能仍在进行。
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.PropertyName == nameof(BookingDate))
{
DisplayBookings();
}
}
更新
起始于 v8.0.0 Preview 3您可以使用部分属性更改方法。
引自博客:
When using [ObservableProperty] to generate observable properties, the MVVM Toolkit will now also generate two partial methods with no implementations: On<PROPERTY_NAME>Changing and On<PROPERTY_NAME>Changed. These methods can be used to inject additional logic when a property is changed, without the need to fallback to using a manual property. Note that because these two methods are partial, void-returning and with no definition, the C# compiler will completely remove them if they are not implemented, meaning that when not used they will simply vanish and add no overhead to the application
然后你可以将其重写为:
[ObservableProperty]
public DateTime bookingDate;
partial void OnBookingDateChanged(DateTime bookingDate)
{
DisplayBookings();
}
关于c# - 如何在属性更新后调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71857854/