好的,所以我试图自学MVVM模式和WPF,并且遇到了麻烦。
我有一个具有“SelectedProduct”字段的ViewModel。设置了SelectedProduct字段后,我想通过调用长时间运行的函数来填充另一个属性“BindedLimits”的内容(这大约需要2到10秒,具体取决于所选择的产品)。理想情况下,我想在后台启动更新,并在发生这种情况时以某种方式显示“进度”窗口,但是我似乎找不到任何可靠的资源来了解如何实现此目的,或者即使是做这种事情的“正确”方法。
到目前为止,这是我的ViewModel ...
public class LimitsViewModel : PropertyChangedBase
{
private ProductFamily selectedProduct;
public ProductFamily SelectedProduct
{
get { return this.selectedProduct; }
set
{
bool runLongOperation = true;
if (value == this.selectedProduct)
{
runLongOperation = false;
}
this.SetPropertyChanged(ref this.selectedProduct, value);
if (runLongOperation)
{
this.Limits = LoadLimits();
}
}
}
private ObservableCollection<BindedLimit> limits;
public ObservableCollection<BindedLimit> Limits
{
get { return this.limits; }
set
{
this.SetPropertyChanged(ref this.limits, value);
}
}
private BindedLimit selectedLimit;
public BindedLimit SelectedLimit
{
get { return this.selectedLimit; }
set
{
this.SetPropertyChanged(ref this.selectedLimit, value);
}
}
private ObservableCollection<BindedLimit> LoadLimits()
{
// Long running stuff here
}
}
最佳答案
就像是
private ProductFamily _selectedProduct;
public ProductFamily SelectedProduct
{
get { return _selectedProduct; }
set
{
this.SetPropertyChanged(ref _selectedProduct, value)
Limits.Clear(); // or Limits = new ...
Task.Run(() => LongTask());
}
}
private void LongTask()
{
var list = new List<BindedLimit>();
...
App.Current.Dispatcher.Invoke(() => Limits = new ObservableCollection<BindedItems>(list));
}
关于c# - 在属性更改启动长期运行任务中填充另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27446297/