在TextBox中查看输入文本一秒钟,然后更改为passwordchar

时间:2015-01-22 15:30:18

标签: c# wpf textbox

与此相同Question,但最后一个答案是我想要的那个..我需要c#wpf ...我尝试了最后一个答案,但我似乎无法获得间隔...有时候关键可以看到按下,有时它不会......按键时怎样才能获得相同的间隔?

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

我试过

dispatcherTimer.Interval = TimeSpan.FromSeconds(5);

但仍然相同......

修改

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 个答案:

答案 0 :(得分:1)

您不需要每次都订阅新的事件处理程序。只需在构造函数中执行一次

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

Keydown事件中,只需重置timer(很遗憾,我们没有任何Reset方法)

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

当计时器打勾时,只需Stop计时器并开始工作

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