我得到了一个名为Box的模型,其中包含一个Customer Property,该属性使用Required DataAnnotation进行修饰。
public class Box : ValidatableBindableBase
{
protected Customer _Customer;
[Required]
public virtual Customer Customer
{
get { return _Customer; }
set { SetProperty(ref _Customer, value); }
}
}
注意:ValidatableBindableBase主要来自https://www.pluralsight.com/blog/software-development/async-validation-wpf-prism
在UI中有一个ComboBox和一个Button。 Combobox ItemsSource是一个客户列表,将在程序启动时通过服务调用填充。
<ComboBox ItemsSource="{Binding Customers,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
SelectedItem="{Binding Path=CurrentBox.Customer,UpdateSourceTrigger=PropertyChanged}" />
Box的Customers属性在程序启动时为NULL。因此,Combobox有一个红色边框(无效)。用户必须单击将执行OnBoxCommand的Button。这也将进行服务调用并设置CurrentBox的Customer属性。
public DelegateCommand<String> BoxCommand { get; private set; }
protected async void OnBoxCommand()
{
CurrentBox.Customer = (await _ServiceCall.GetCustomer());
}
执行OnBoxCommand后,ComboBox仍然显示红色边框,显然客户端已在UI中设置。当我在_ServiceCall.GetCustomer();
行之后使用调试器时,我看到CurrentBox.HasErrors为false,并且设置了CurrentBox.Customer。我还试图添加到绑定&#34; ValidatesOnException = True&#34;并调用CurrentBox.ValidateProperties();
几个小时后,我通过在任务中分配ServiceCall的值来找到解决方案。
protected async void OnBoxCommand()
{
var bla = (await _ServiceCall.GetCustomer());
new Task(() => this.CurrentBox.Customer = bla).Start();
}
我不知道为什么没有任务就没有更新wpf控件的验证。有人知道这种奇怪的行为,可以解释为什么我需要使用new Task(() => this.CurrentBox = bla).Start();
答案 0 :(得分:0)
await _ServiceCall.GetCustomer();
将返回Task<Customer>
。要从服务电话中获取客户,您必须调用任务的结果
protected async void OnBoxCommand()
{
this.CurrentBox = await _ServiceCall.GetCustomer().Result;
}