简体   繁体   English

区分由用户输入Vs触发的事件。 UWP背后的代码

[英]Distinguish Between Events Triggered by User Input Vs. Code Behind UWP

I have a CheckBox in a UWP app that is manipulated by both the user and code behind. 我在UWP应用中有一个CheckBox,它由用户和背后的代码操纵。 When the user checks it, I do want the Checked event to fire. 当用户检查它时,我确实希望触发Checked事件。 However, when the code behind checks it (like below), I don't want it to fire. 但是,当后面的代码对其进行检查时(如下所示),我不希望它触发。

checkBoxExample.isChecked = true; //The Checked event should not fire.

I figured I would get this information from either the sender (object) or e (RoutedEventArgs) but it isn't there. 我想我将从发件人(对象)或e(RoutedEventArgs)那里获得此信息,但是它不存在。

You could just add a flag that you then set to avoid processing the event: 您可以添加一个标志,然后将其设置为避免处理事件:

private bool _checkedFromCode = false;

private void CheckboxChecked(object sender, RoutedEventArgs e)
{
    if ( !_checkedFromCode )
    {
        //your logic
    }
}

Now when setting the IsChecked from code: 现在,通过代码设置IsChecked时:

_checkedFromCode = true;
checkBoxExample.IsChecked = true;
_checkedFromCode = false;

The event will still fire, but you can limit the processing to only when it actually is from the user interaction. 该事件仍然会触发,但是您可以将处理限制为仅在实际上来自用户交互时才进行。

Alternatively, you could create a custom derived version of CheckBox that would have a custom event only for this scenario. 或者,您可以创建CheckBox的自定义派生版本,该版本仅具有针对此方案的自定义事件。

RE: Tapped event : The suggested solution with Tapped event would not work as you should not presume the user is using touch, mouse or pen, as Windows 10 works with any kind of input, so the only reliable event is the Checked event. RE: Tapped 事件 :由于Windows 10可以处理任何类型的输入,因此您不应该假定用户正在使用触摸,鼠标或笔,因此建议的Tapped事件解决方案将不起作用,因此唯一可靠的事件是Checked事件。 It should not matter which input type you use. 使用哪种输入类型都无关紧要。 This is especially true to make your app accessible and inclusive. 为了使您的应用程序具有可访问性和包容性,尤其如此。 Keyboard, for example, does not cause Tapped event. 例如,键盘不会引起Tapped事件。

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

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