当用户在文本框中键入一个字符时通知ViewModel
问题描述:
我正在用C#,.NET Framework 4.5.1和MVVM模式开发WPF。当用户在文本框中键入一个字符时通知ViewModel
我有这个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
吗?
答
在你的绑定,指定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}"/>
如果要查看Binding的文档,比写这个问题花费的时间要少。 – Will 2014-10-02 15:06:23