Ste*_*cya 49
您必须实现INotifyPropertyChanged
并添加绑定到文本框.
我将提供C#代码段.希望能帮助到你
class Sample : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
InvokePropertyChanged(new PropertyChangedEventArgs("FirstName"));
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
用法:
Sample sourceObject = new Sample();
textbox.DataBindings.Add("Text",sourceObject,"FirstName");
sourceObject.FirstName = "Stack";
Run Code Online (Sandbox Code Playgroud)
一个简化版本接受的答案的,不需要你在每一个属性setter喜欢手动键入属性的名称OnPropertyChanged("some-property-name")
。相反,您只是OnPropertyChanged()
不带参数调用:
您至少需要.NET 4.5。
CallerMemberName
在System.Runtime.CompilerServices
名称空间中
public class Sample : INotifyPropertyChanged
{
private string _propString;
private int _propInt;
//======================================
// Actual implementation
//======================================
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
//======================================
// END: actual implementation
//======================================
public string PropString
{
get { return _propString; }
set
{
// do not trigger change event if values are the same
if (Equals(value, _propString)) return;
_propString = value;
//===================
// Usage in the Source
//===================
OnPropertyChanged();
}
}
public int PropInt
{
get { return _propInt; }
set
{
// do not allow negative numbers, but always trigger a change event
_propInt = value < 0 ? 0 : value;
OnPropertyChanged();
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法保持不变:
var source = new Sample();
textbox.DataBindings.Add("Text", source, "PropString");
source.PropString = "Some new string";
Run Code Online (Sandbox Code Playgroud)
希望这对某人有帮助。
归档时间: |
|
查看次数: |
49193 次 |
最近记录: |