简体   繁体   English

这将在WPF控件中首先触发Binding触发器或Event

[英]Which will fire first Binding trigger or Event in WPF control

I am forced to use a third party control for masking the text input. 我被迫使用第三方控件来掩盖文本输入。 The XAML for the third party control looks like this 第三方控件的XAML如下所示
<thirdParty:MaskInput Value={Binding Path=Phone, UpdateSourceTrigger=LostFocus} x:Name=Phone LostFocus=Phone_LostFocus />

Now in my code behind I have a code for the event handler like this - 现在在我的代码后面,我有一个这样的事件处理程序代码-
public void Phone_LostFocus(object sender, RoutedEventArgs e) { ((MaskInput)sender).Value = ((MaskInput)e.OriginalSource).Text; }

When I execute this code some times the Value property is set and some times it is not set to the text. 当我执行此代码时,有时设置了Value属性,而有时未将其设置为文本。

I suspect the Binding's UpdateSourceTrigger. 我怀疑绑定的UpdateSourceTrigger。 Should I change it to something else? 我应该将其更改为其他内容吗? What is the order in cases like these between the UpdateSourceTrigger and event itself? 在这种情况下,UpdateSourceTrigger和事件本身之间的顺序是什么? Is that order predictable ie does it always happens in that order? 该顺序是可预测的,即是否总是以该顺序发生?

I assume you need the changes when your LostFocus event is called? 我假设在调用LostFocus事件时需要更改吗?

There are a few things you can do here, because as far as I know, the order is not predictable between an UpdateSourceTrigger of LostFocus and an event of LostFocus. 您可以在此处执行一些操作,因为据我所知,在LostFocus的UpdateSourceTrigger和LostFocus事件之间的顺序是不可预测的。

1.Update the source trigger at a different time. 1.在其他时间更新源触发器。 If you do it when the property changes, your model will already be updated by the time your LostFocus event is called. 如果在属性更改时执行此操作,则在调用LostFocus事件时,模型将已经更新。 The drawback is that if you are doing a lot of processing behind the scenes every time the model is updated, this will run slowly. 缺点是,如果每次更新模型时都在后台进行大量处理,则该过程将运行缓慢。

<thirdParty:MaskInput Value={Binding Path=Phone, UpdateSourceTrigger=PropertyChanged} LostFocus=Phone_LostFocus/>

2.Propagate the changes to your model in the LostFocus event and leave your binding as OneWay (from model to control). 2.在LostFocus事件中传播对模型的更改,并将绑定保留为OneWay(从模型到控件)。

<thirdParty:MaskInput Value={Binding Path=Phone, Mode=OneWay}, LostFocus=Phone_LostFocus/>

public void Phone_LostFocus(object sender, RoutedEventArgs e) { 
    myPhone.Value = ((MaskInput)sender).Text;
    //rest of event code here.
}

3.Use the MaskInput value in the LostFocus event, and don't worry about when the model gets its changes. 3.在LostFocus事件中使用MaskInput值,不必担心模型何时发生更改。

<thirdParty:MaskInput Value={Binding Path=Phone, UpdateSourceTrigger=LostFocus}, LostFocus=Phone_LostFocus/>

public void Phone_LostFocus(object sender, RoutedEventArgs e) { 
    string currentText = ((MaskInput)sender).Text;
    //rest of event using currentText;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM