View Input Text for a second in TextBox and change

2019-08-09 19:47发布

问题:

same Question as this one but the last answer is the one i wanted.. I need c# wpf... i tried the last answer but i can't seem to get the interval.. sometimes the key pressed can be seen, and sometimes it doesn't.. how can I get same interval when key press?

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1);
    dispatcherTimer.Start();
}

i tried

dispatcherTimer.Interval = TimeSpan.FromSeconds(5);

but still the same...

EDIT

private void dispatcherTimer_Tick(object sender, EventArgs e)
{   
    string str = "";
    for(int i = 0; i < txtPass.Text.Length; i++)
        str += char.ConvertFromUtf32(8226);

    txtPass.Text = str;
    txtPass.Select(txtPass.Text.Length, 0);
}

回答1:

You don't need to subscribe to new event handler every time. Just do it one time in the constructor

dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1);

In the Keydown event, just reset the timer (Unfortunately we don't have any Reset method)

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    dispatcherTimer.Stop();
    dispatcherTimer.Start();
}

As the timer ticks, just Stop the timer and do your work

void dispatcherTimer_Tick(object sender, EventArgs e)
{
    dispatcherTimer.Stop();
    //your code
}


标签: c# wpf textbox