我正在使用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
?
答案 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}"/>