WPF:简单的TextBox数据绑定
我有这个类:
public partial class Window1 : Window
{
public String Name2;
public Window1()
{
InitializeComponent();
Name2 = new String('a', 5);
myGrid.DataContext = this;
}
// ...
}
我想在文本框中显示字符串 Name2
。
And I want to display the string Name2
in the textbox.
<Grid Name="myGrid" Height="437.274">
<TextBox Text="{Binding Path=Name2}"/>
</Grid>
但是字符串不显示。另外,如果使用 TimerCallback
定期更新字符串 Name2
,那么我需要做任何事情来确保文本框数据更改时更新?
But the string isn't displayed. Also, if the string Name2
is updated periodically using a TimerCallback
, do I need to do anything to make sure the textbox is updated when the data changes?
Name2是一个字段。 WPF仅绑定到属性。更改为:
Name2 is a field. WPF binds only to properties. Change it to:
public string Name2 { get; set; }
Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:
partial class Window1 : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// usual OnPropertyChanged implementation
private string _name2;
public string Name2
{
get { return _name2; }
set
{
if (value != _name2)
{
_name2 = value;
OnPropertyChanged("Name2");
}
}
}
}
你应考虑将其移动到单独的数据对象而不是Window类。
You should consider moving this to a separate data object rather than on your Window class.