我正在创建一个使用多个线程的应用程序,因此我想尽可能少地尝试在我的代码中使用UIControls。我这样做的方式是通过将控件绑定到代码中的属性,这样我就可以通过更改该属性来更新控件,如果该属性在不同的线程上更新,则无关紧要。无论如何,我正在创建以下代码,以便该类从我这里创建绑定。将控件绑定到属性不起作用
public static class MyExtensionMethods
{
public static TextBoxBind<T> BindTextBox<T>(this TextBox textbox, string property=null)
{
return new TextBoxBind<T>(textbox,property);
}
}
public class TextBoxBind<T> : INotifyPropertyChanged
{
string property;
protected T _Value;
public T Value
{
get { return _Value; }
set { _Value = value; OnPropertyChanged(property); }
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void OnPropertyChanged(string propertyName){
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public TextBoxBind(TextBox textbox, string property)
{
if (property == null)
{
property = "Value";
}
this.property = property;
Binding b = new Binding(property)
{
Source = this
};
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
textbox.SetBinding(TextBox.TextProperty, b);
}
}
而且在我的XAML我:
<TextBox Name="textBox2" />
因此,我将能够使用自己发布的第一个代码为:
var newTextBox2 = textBox2.BindTextBox<int>();
newTextBox2.Value = 50; // this will update the textBox2.Text = "2"
// also every time I update the value of textBox2 newTextBox2.Value will update as well
问题是,当我尝试将它绑定到一个自定义对象。拿这个代码,例如:
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public override string ToString()
{
return Age.ToString();
}
}
void LogIn_Loaded(object sender, RoutedEventArgs e)
{
txtUsuario.Focus();
var newTextBox2 = textBox2.BindTextBox<Person>("Age");
// here newTextBox2 never updates....
}
我知道如何使用dispacher感谢您的帮助。如果你将一个属性绑定到一个UIcontrol,你将能够在一个单独的线程上更新该属性而不会产生异常。此外,你可以在UIcontrols上验证... – 2012-03-18 08:30:48