几个解决方案(第一个和第二个不使用数据绑定)。
txtMyControl.text = "New value";
如果不在主线程上,您可以使用调度程序来更新值。
Application.Current.Dispatcher.BeginInvoke(() => txtMyControl.text == "New Value")
然而,最友好的 WPF 方法是使用数据绑定。
对代码中的值所做的任何更改都会立即反映在 UI 中。
XAML
<TextBox x:Name="txtExample" Text="{Binding MyTextProperty,Mode=TwoWay}" Height="24" Width="120"/>
在您的代码中,您必须声明一个持久的变量。
private ExampleModel _ExampleModel = new ExmampleModel();
当您加载代码时,将该变量与您的文本框数据上下文相关联。
txtExample.DataContext = _ExampleModel
然后,您将拥有一个包含屏幕上所有可编辑属性(文本框、单选框等)的类
public class ExampleModel : INotifyPropertyChanged
{
private string _MyTextProperty = "test";
public string MyTextProperty {
get { return _MyTextProperty; }
set {
if (string.Compare(_MyTextProperty, value) != 0) {
_MyTextProperty = value;
RaisePropertyChanged("MyTextProperty");
}
}
}
public void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
public event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;
public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);
}
每当您处理您的事件时,您只需更改包含信息的属性的值,UI 就会相应地刷新。此外,由于我们使用双向绑定,因此您的文本框中的值将始终与 ExampleModel 类中 MyTextProperty 属性包含的值相同,这使得值检索非常容易。
例如:
_ExampleModel.MyTextProperty = "New value";
如果您已经在使用数据绑定,请确保使用的类实现了 INotifyPropertyChanged,并且在属性值更改时调用 propertyChanged 事件,否则它不会更新 UI。