【问题标题】:Notify ViewModel when user types a character on textbox当用户在文本框中输入字符时通知 ViewModel
【发布时间】:2014-10-02 22:58:14
【问题描述】:

我正在使用 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

【问题讨论】:

  • 查看 Binding 文档所花费的时间比编写此问题所花费的时间要少。

标签: c# wpf mvvm mvvm-light


【解决方案1】:

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

【讨论】:

    【解决方案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}"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多