问题描述
我有一个文本框,其值是绑定到一个ViewModel属性:
I have a TextBox whose Value is binded to a ViewModel property:
<TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding Mode=TwoWay, Path=RunAfter}" Style="{StaticResource TestStepTextBox}"/>
设置和直到我尝试添加时,该值设置一些验证得到了工作的罚款:
The set and get were working fine until I tried to add some validation when the Value is set:
private int _runAfter = 0;
public string RunAfter
{
get
{
return _runAfter.ToString();
}
set
{
int val = int.Parse(value);
if (_runAfter != val)
{
if (val < _order)
_runAfter = val;
else
{
_runAfter = 0;
OnPropertyChanged("RunAfter");
}
}
}
}
虽然达到OnPropertyChanged(我dubugged了),视图不会改变。
我怎样才能使这项工作?
Although the OnPropertyChanged is reached (I have dubugged that), the View is not changed.How can I make this work?
谢谢,
何塞·塔瓦雷斯
Thanks,José Tavares
推荐答案
的问题是,在更新源中的绑定
,而结合
正在更新你的财产。 WPF实际上不会检查你的财产的价值时,它提出了一个的PropertyChanged
事件响应绑定
更新。您可以通过使用调度
延迟事件的传播中的一个分支,解决这个问题:
The problem is that you are updating the source for the Binding
while the Binding
is updating your property. WPF won't actually check your property value when it raises the PropertyChanged
event in response to a Binding
update. You can solve this by using the Dispatcher
to delay the propagation of the event in that branch:
set
{
int val = int.Parse(value);
if (_runAfter != val)
{
if (val < _order)
{
_runAfter = val;
OnPropertyChanged("RunAfter");
}
else
{
_runAfter = 0;
Dispatcher.CurrentDispatcher.BeginInvoke(
new Action<String>(OnPropertyChanged),
DispatcherPriority.DataBind, "RunAfter");
}
}
}
更新:
我注意到的另一件事是,绑定
在文本框
使用默认 UpdateSourceTrigger
,它发生在当文本框
失去焦点。你不会看到文字变回0,直到文本框后
失去焦点,与此模式。如果您将其更改为的PropertyChanged
,你会看到这个立即发生。否则,你的财产将不会被置直到你的文本框
失去焦点:
The other thing I noticed is that the Binding
on your TextBox
is using the default UpdateSourceTrigger
, which happens when the TextBox
loses focus. You won't see the text change back to 0 until after the TextBox
loses focus with this mode. If you change it to PropertyChanged
, you will see this happen immediately. Otherwise, your property won't get set until your TextBox
loses focus:
<TextBox Name="txtRunAfter" Grid.Column="4" Text="{Binding RunAfter, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource TestStepTextBox}"/>
这篇关于WPF文本框的值不会改变OnPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!