用户在文本框中键入字符时通知ViewModel

本文关键字:字符 通知 ViewModel 文本 用户 | 更新日期: 2023-09-27 18:25:25

我正在用C#、.NET Framework 4.5.1和MVVM模式开发一个WPF。

我有这个TextBox:

<TextBox 
    x:Name="userName" 
    HorizontalAlignment="Left" 
    Height="23" 
    TextWrapping="Wrap" 
    VerticalAlignment="Top" 
    Width="231" 
    Margin="10,10,0,5" 
    Text="{Binding Path=UserName, Mode=TwoWay}"/>

这就是属性:

/// <summary>
/// The <see cref="UserName" /> property's name.
/// </summary>
public const string UserNamePropertyName = "UserName";
private string _userName = null;
/// <summary>
/// Sets and gets the UserName property.
/// Changes to that property's value raise the PropertyChanged event. 
/// </summary>
public string UserName
{
    get
    {
        return _userName;
    }
    set
    {
        if (_userName == value)
        {
            return;
        }
        RaisePropertyChanging(UserNamePropertyName);
        _userName = value;
        RaisePropertyChanged(UserNamePropertyName);
        DoLoginCommand.RaiseCanExecuteChanged();
    }
}

我的问题是,在TextBox失去焦点之前,我无法获得新值。

当用户在TextBox上键入字符时,有什么方法可以通知ViewModel吗?

用户在文本框中键入字符时通知ViewModel

在绑定中,指定UpdateSourceTrigger=PropertyChanged

<TextBox 
    x:Name="userName" 
    HorizontalAlignment="Left" 
    Height="23" 
    TextWrapping="Wrap" 
    VerticalAlignment="Top" 
    Width="231" 
    Margin="10,10,0,5" 
    Text="{Binding Path=UserName, UpdateSourceTrigger=PropertyChanged}"/>

问题在于您的绑定,

我相信您所需要做的就是将"UpdateSourceTrigger="PropertyChanged"添加到绑定中,使其如下所示:

<TextBox 
    x:Name="userName" 
    HorizontalAlignment="Left" 
    Height="23" 
    TextWrapping="Wrap" 
    VerticalAlignment="Top" 
    Width="231" 
    Margin="10,10,0,5" 
    Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>