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

时间:2014-10-02 14:53:23

标签: c# wpf mvvm mvvm-light

我正在使用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失去焦点之前,我无法获得新值。

当用户在ViewModel上输入字符时,有没有办法通知TextBox

2 个答案:

答案 0 :(得分:2)

在绑定中,指定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}"/>

答案 1 :(得分:2)

问题在于您的绑定,

我相信您需要做的就是将“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}"/>
相关问题