我正试图从WinForms迁移到WPF,并且我仍然坚持使用绑定。
我有一个标签:
<Label Name="labelState" Content="{Binding state}" HorizontalAlignment="Right" Margin="10,10,10,10" FontSize="12" />
在同一个userControl(名为FormInput)的cs中,我有:
public string state { get; set; }
public FormInput()
{
state = "ok";
InitializeComponent();
}
为什么这不起作用?
谢谢。
答案 0 :(得分:0)
当您在WPF中绑定某些内容时,您需要使用 INotifyPropertyChanged
实现一个类,
class TestObject : INotifyPropertyChanged
{
private string _state;
public string State
{
get
{
return _state;
}
set
{
if (_state == value) return;
_state = value;
OnPropertyChanged("State");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
并在 FormInput
public FormInput()
{
InitializeComponent();
TestObject t = new TestObject();
labelState.DataContext = t;
t.State = "ok";
}
和XAML如下,
<Label Name="labelState" Content="{Binding State}" HorizontalAlignment="Right" >