我在显示通过ComboBox选择过滤的图形而没有UI锁定时遇到问题.统计过滤非常繁重,需要运行异步.这一切都很好,直到我尝试从Property setter调用FilterStatisticsAsync和MonthSelectionChanged.有没有人对如何解决或解决这个问题有一个很好的建议?
XAML看起来像这样:
<ComboBox x:Name="cmbMonth" ItemsSource="{Binding Months}" SelectedItem="{Binding SelectedMonth }" IsEditable="True" IsReadOnly="True"
public string SelectedMonth { get { return _selectedMonth; } set { SetProperty(ref _selectedMonth,value); LoadStatisticsAsync(); MonthSelectionChanged(); } }
SetProperty派生自一个封装INPC的基类,如下所示:
public event PropertyChangedEventHandler PropertyChanged = delegate { }; protected virtual void SetProperty<T>(ref T member,T value,[CallerMemberName] string propertyName = null) { if (Equals(member,value)) return; member = value; PropertyChanged(this,new PropertyChangedEventArgs(propertyName)); }
解决方法
我会这样做:
public class AsyncProperty<T> : INotifyPropertyChanged { public async Task UpdateAsync(Task<T> updateAction) { LastException = null; IsUpdating = true; try { Value = await updateAction.ConfigureAwait(false); } catch (Exception e) { LastException = e; Value = default(T); } IsUpdating = false; } private T _value; public T Value { get { return _value; } set { if (Equals(value,_value)) return; _value = value; OnPropertyChanged(); } } private bool _isUpdating; public bool IsUpdating { get { return _isUpdating; } set { if (value == _isUpdating) return; _isUpdating = value; OnPropertyChanged(); } } private Exception _lastException; public Exception LastException { get { return _lastException; } set { if (Equals(value,_lastException)) return; _lastException = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName)); } }
财产的定义
public AsyncProperty<string> SelectedMonth { get; } = new AsyncProperty<string>();
你代码中的其他地方:
SelectedMonth.UpdateAsync(Task.Run(() => whateveryourbackground work is));
在xaml中绑定:
SelectedItem="{Binding SelectedMonth.Value }"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。