MVVMを使用すると、非常に簡単になります。
- ViewModel で文字列プロパティを宣言します。
- プロパティをこの文字列プロパティにバインドし、
TextBox.Text
UpdateSourceTrigger を PropertyChanged に、モードを TwoWay に設定します。
- ViewModel でプロパティが変更されるたびにロジックを実行します。
ビューモデル
public class MyViewModel : INotifyPropertyChanged
{
private string someText;
public string SomeText
{
get
{
return this.someText;
}
set
{
this.someText = value;
if (SomeCondition(this.someText))
{
this.someText = string.Empty;
}
var epc = this.PropertyChanged;
if (epc != null)
{
epc(this, new PropertyChangedEventArgs("SomeText"));
}
}
}
}
XAML
<TextBox Text="{Binding SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>