好的,我试着教自己MVVM模式和WPF,我遇到了一个块。
我有一个ViewModel,它有一个"SelectedProduct“字段。当设置该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
}
}发布于 2014-12-12 15:34:14
有点像
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));
}发布于 2014-12-12 15:40:57
Sinatr与What's the best way to update an ObservableCollection from another thread?的链接帮助我找到了解决方案。这是我设计的。谢谢!
public class LimitsViewModel : PropertyChangedBase
{
private CancellationTokenSource tokenSource;
public LimitsViewModel()
{
this.tokenSource = new CancellationTokenSource();
}
public ICommand LoadCommand
{
get { return new RelayCommand(async x => await this.LoadLimits(this.tokenSource.Token)); }
}
private ProductFamily selectedProduct;
public ProductFamily SelectedProduct
{
get { return this.selectedProduct; }
set
{
this.SetPropertyChanged(ref this.selectedProduct, value);
this.LoadCommand.Execute(null);
}
}
private ObservableCollection<BindedLimit> limits;
public ObservableCollection<BindedLimit> Limits
{
get { return this.limits; }
set { this.SetPropertyChanged(ref this.limits, value); }
}
private bool limitsLoading;
public bool LimitsLoading
{
get { return this.limitsLoading; }
set { this.SetPropertyChanged(ref this.limitsLoading, value); }
}
private BindedLimit selectedLimit;
public BindedLimit SelectedLimit
{
get { return this.selectedLimit; }
set { this.SetPropertyChanged(ref this.selectedLimit, value); }
}
private async Task LoadLimits(CancellationToken ct)
{
}
}https://stackoverflow.com/questions/27446297
复制相似问题