事件中区分是代码更改还是用户更改

事件中区分是代码更改还是用户更改

本文介绍了如何在 C# 事件中区分是代码更改还是用户更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个简单的 TextBox 一开始是空的.我有一个简单的事件 _TextChanged,用于了解用户何时更改了 TextBox 中的任何内容.但是,如果我自己在代码中对其进行任何操作,则会触发该事件.像设置 textbox.Text = "Test"; 或类似的.

I have a simple TextBox that is empty in the beginning. I have a simple event, _TextChanged, to know when the user changed anything in that TextBox. However, the event fires if I do anything with it myself from within code. Like setting textbox.Text = "Test"; or similar.

    private void textNazwa_TextChanged(object sender, EventArgs e) {
        changesToClient = true;
    }

如何使事件仅在用户交互时触发,而不在代码更改时触发?

How do I make the event only fire on user interaction and not code changes?

推荐答案

事件本身不会区分通过用户输入输入的文本和通过代码更改的文本.您必须自己设置一个标志,告诉您的代码忽略该事件.例如,

The event itself does not make a distinction between text entered via user input and text changed via code. You'll have to set a flag yourself that tells your code to ignore the event. For example,

private bool ignoreTextChanged;

private void textNazwa_TextCanged(object sender, EventArgs e)
{
    if (ignoreTextChanged) return;
}

然后使用它来设置文本而不是仅仅调用 Text = "...";:

Then use this to set the text instead of just calling Text = "...";:

private void SetTextboxText(string text)
{
    ignoreTextChanged = true;

    textNazwa.Text = text;

    ignoreTextChanged = false;
}

从你对另一个答案的评论来看,听起来你有很多文本框.在这种情况下,您可以这样修改函数:

Judging by your comment to another answer, it sounds like you have quite a number of textboxes. In that case, you could modify the function in this way:

private void SetTextBoxText(TextBox box, string text)
{
    ignoreTextChanged = true;

    box.Text = text;

    ignoreTextChanged = false;
}

然后这样称呼它:

SetTextBoxText(textNazwa, "foo");

这将完成与仅执行 textNazwa.Text = "foo" 相同的事情,但会设置标志让您的事件处理程序知道忽略该事件.

This would accomplish the same thing as just doing textNazwa.Text = "foo", but will set the flag letting your event handler know to ignore the event.

这篇关于如何在 C# 事件中区分是代码更改还是用户更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:02