6

我使用 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 事件。我怎样才能做到这一点?我应该使用什么组件?

4

1 回答 1

15
 <TextBox Name="textBox1"
      Height="23" Width="463"
      HorizontalAlignment="Left" 
      Margin="12,12,0,0"   
      VerticalAlignment="Top"
      Text="{Binding OriginalText, UpdateSourceTrigger=PropertyChanged}" /> 

MSDN 如何:控制 TextBox 文本何时更新源

TextBox.Text属性的默认UpdateSourceTrigger值为 LostFocus。这意味着如果应用程序有一个带有数据绑定 TextBox.Text 属性的 TextBox,则您在 TextBox 中键入的文本不会更新源,直到 TextBox 失去焦点(例如,当您单击离开 TextBox 时)。

如果您希望在键入时更新源,请将绑定的 UpdateSourceTrigger 设置为PropertyChanged。在以下示例中,TextBox 和 TextBlock 的 Text 属性绑定到相同的源属性。TextBox 绑定的UpdateSourceTrigger 属性设置为PropertyChanged。

于 2012-07-17T12:29:26.057 回答