我使用 XAML 和数据绑定 (MVVM)。当我的用户在 TextBox 中写入新的文本字符时,我需要更新标签。
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="463" Text="{Binding OriginalText}"/>
<Label Height="28" HorizontalAlignment="Left" Margin="12,41,0,0" Name="label1" VerticalAlignment="Top" Width="463" Content="{Binding ModifiedText}"/>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="400,276,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
视图模型
class MainViewModel : NotifyPropertyChangedBase
{
private string _originalText = string.Empty;
public string OriginalText
{
get { return _originalText; }
set
{
_originalText = value;
NotifyPropertyChanged("OriginalText");
NotifyPropertyChanged("ModifiedText");
}
}
public string ModifiedText
{
get { return _originalText.ToUpper(); }
}
}
我在 XAML 中添加了一个按钮。该按钮什么都不做,只是帮助我失去了文本框的焦点。当我失去焦点时,绑定会更新,上面的文本会出现在我的标签中。但是数据绑定只有在文本失去焦点时才会更新。TextChanged 事件不会更新绑定。我想强制更新 TextChanged 事件。我怎样才能做到这一点?我应该使用什么组件?