最近我一直在使用 MVVM Light 开发一个应用程序。我的 XAML 中绑定了一个 TextBox 到我的 UI上。我想验证输入并确保只能输入数字。我尝试了以下代码:
我的 TextBox:
<TextBox TabIndex="1" Height="23" MinWidth="410" DockPanel.Dock="Left"
HorizontalAlignment="Left"
Text="{Binding Input, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsEnabled}"
AcceptsReturn="False"
local:FocusExtension.IsFocused="{Binding IsFocused}">
在我的ViewModel中:
private string input;
public string Input
{
get { return this.input; }
set
{
decimal test;
if(decimal.TryParse(value, out test))
{
this.input = value;
}
else
{
this.input = "";
}
RaisePropertyChanged("Input");
}
}
这段代码无法更新UI。如果我输入"B"并检查调试器,它会运行setter方法,但是无法实际更新UI。
有趣的是,如果我在else块中设置this.input = "TEST";
,则UI将更新,但是,如果我尝试将其设置为""、string.Empty或验证之前的输入值,则UI将无法更新。
这是否是设计上的问题?可能是个bug吗?我做错了什么吗?
编辑 我错误地忘记在示例代码中包括RaisePropertyChanged
。我已经更新了代码。唤起它不是问题,因为我观察调试器一直运行唤起它并通过getter返回input。
OnPropertyChanged
。这个类实现了IPropertyChanged
接口吗? - Mike PerrenoudRaisePropertyChanged
。我不小心忘了将其放入问题中的代码中。 - DanteTheEgregore