WPF 文本框使用默认文本

发布于 2024-10-17 05:04:24 字数 150 浏览 2 评论 0原文

我有一个文本框,我希望用户以 XX:XX:XX 格式输入时间值。我已经进行了验证,以确保他们以这种格式输入。但是,现在我想自动将冒号放在那里。我希望它们位于文本框中,当用户输入数字时,他们只是跳过冒号。是否可以为文本框提供某种格式装饰器?

编辑:我正在使用 WPF 4。

I have a TextBox, which I want my users to enter a time value in the format XX:XX:XX. I already have validation in place to make sure they enter it in this format. However, now I'd like to have the colons there automatically. I'd like them to be in the textbox, and as the user types numbers, they just skip over the colons. Is it possible to have some kind of format decorator for the TextBox?

EDIT: I am using WPF 4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴情 2024-10-24 05:04:24

如果您想坚持使用普通 WPF,您可以创建一个自定义控件并添加 3 个文本框。

在它们之间放置冒号并处理 keydown 事件,将焦点从一个文本框传递到另一个文本框,同时仅接受数字。

再次强调:使用工具包可能会减少工作量。

If you want to stick to vanilla WPF you could create a Custom Control and add 3 textboxes.

Put colons in between them and handle the keydown events to pass focus from one textbox to the other and at the same time accepting numbers only.

Again: using the toolkit might be less work.

永不分离 2024-10-24 05:04:24

按照 Erno 建议使用三个文本框可能是更好的解决方案,但您也可以使用 TextChanged 事件向文本添加冒号(这可能会让用户感到困惑),这里是插入它们的代码在第二个和第五个字符之后:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (e.Changes.Count == 1)
    {
        if (e.Changes.ElementAt(0).AddedLength == 1 && (tb.Text.Length == 2 || tb.Text.Length == 5))
        {
            tb.Text += ":";
            tb.SelectionStart = tb.Text.Length;
        }
    }
}

Using three TextBoxes as Erno suggested is probably a better solution but you could also use the TextChanged event to add colons to the text (which might confuse the user), here'd be the code that would insert them after the second and fifth character:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (e.Changes.Count == 1)
    {
        if (e.Changes.ElementAt(0).AddedLength == 1 && (tb.Text.Length == 2 || tb.Text.Length == 5))
        {
            tb.Text += ":";
            tb.SelectionStart = tb.Text.Length;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文