【发布时间】:2015-09-09 17:26:45
【问题描述】:
我有一个包含员工属性的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace SimpleDatabinding03
{
public class Employee:INotifyPropertyChanged
{
int _employeenumber;
string _firstname;
string _lastname;
string _dept;
string _title;
//constructor
public Employee()
{
}
//properties
public int EmployeeNum
{
get { return _employeenumber; }
set { _employeenumber = value; NotifyPropertyChanged("EmployeeNum"); }
}
public string FirstName
{
get { return _firstname; }
set { _firstname = value; NotifyPropertyChanged("FirstName"); }
}
public string LastName
{
get { return _lastname; }
set { _lastname = value; NotifyPropertyChanged("LastName"); }
}
public string Dept
{
get { return _dept; }
set { _dept = value; NotifyPropertyChanged("Dept"); }
}
public string Title
{
get { return _title; }
set { _title = value; NotifyPropertyChanged("Title"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyname)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
//internal object GetBindingExpression(System.Windows.DependencyProperty dependencyProperty)
//{
// throw new NotImplementedException();
//}
}
}
在 XAML 中,我将它们绑定到一个文本框:
<Grid>
<Grid.DataContext>
<m:Employee x:Name="employee"/>
</Grid.DataContext>
<Label Grid.Row="0">Employee Number</Label>
<TextBox Name="EmpNum" Grid.Row="0" Grid.Column="1" Text="{Binding EmployeeNum}" ></TextBox>
<Label Grid.Row="2" >first name</Label>
<TextBox Name="Fname" Grid.Row="2" Grid.Column="1" Text="{Binding FirstName}"></TextBox>
<Label Grid.Row="3" >Last name</Label>
<TextBox Name="Lname" Grid.Row="3" Grid.Column="1" Text="{Binding LastName}"></TextBox>
<Label Grid.Row="4" >Dept</Label>
<TextBox Name="Dept" Grid.Row="4" Grid.Column="1" Text="{Binding Dept}"></TextBox>
</Grid>
后面的代码是:
private void button1_Click(object sender, RoutedEventArgs e)
{
employee.EmployeeNum = 123;
System.Threading.Thread.Sleep(3000);
employee.FirstName = "John";
System.Threading.Thread.Sleep(3000);
employee.LastName = "kepler"; });
}
要求:当属性更改时,绑定到员工实例的 UI 文本框不会更新。它等待按钮单击事件完成,然后更新 UI。我正在寻找一种即时更新 UI 的解决方案。
【问题讨论】:
-
那你在问什么?另外,你有没有尝试过让它工作?
-
好吧,您正在将当前线程置于您的代码设置属性的位置。这就是为什么您的 UI 没有更新的原因,它在同一个线程中。尝试创建另一个线程或异步方法。
-
因此,当属性发生变化时,UI 需要立即更新,而不应等待按钮单击完成。注意:尝试使用 UpdateSourceTrigger=PropertyChanged 仍然没有帮助。
-
您使用的是哪个版本的 .Net?
-
@OmegaMan 3.5 版