gpt4 book ai didi

c# - 在不影响光标位置的情况下将 TextBox 输入限制为特定值

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:50 24 4
gpt4 key购买 nike

我有一个 WPF 应用程序 (MVVM)。我想限制用户在 TextBox 中输入超过特定值的值。假设该值为 '100' ,那么用户不应该输入 101 等。我尝试了以下代码。

XAML:

<TextBox Text="{Binding SearchText}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" Name="SearchTextBox"  TextChanged="TextBox_TextChanged"/>

代码:

 private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null && !string.IsNullOrEmpty(textBox.Text))
{
int searchIndex = 0;
int count = 100;
int.TryParse(textBox.Text, out searchIndex);

if (textBox != null && !string.IsNullOrEmpty(textBox.Text))
{
if (searchIndex > Count)
{
textBox.Text = textBox.Text.Substring(0, textBox.Text.Length - 1);
}
}
}
}

使用此代码,我可以限制用户输入超过特定值的值。但问题是,当我设置 TextBox 的文本时,光标会移动到第一个数字。有解决办法吗?

最佳答案

您可以处理 PreviewTextInput 事件,并在验证时将 TextCompositionEventArgsHandled 属性设置为 true失败:

private void SearchTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
string text = textBox.Text + e.Text;
if (!string.IsNullOrEmpty(text))
{
int searchIndex = 0;
int count = 100;
int.TryParse(text, out searchIndex);
e.Handled = (searchIndex > count);
}
}
}

Thanks. You answer has solved my most of the issues. But still if I delete first digit and enter another digit, then the validation fails. Suppose count is 150. I enter 150 & then delete 1 & again enter 1 then textbox will get 501 & validation will fail

好吧,毕竟您应该坚持处理 TextChanged 事件。试试这个:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
const int count = 100;
int searchIndex = 0;
int.TryParse(textBox.Text, out searchIndex);
if (searchIndex > count)
{
var textChange = e.Changes.First();
if (textChange != null && textChange.AddedLength > 0)
{
int caret = textBox.CaretIndex;
int length = textBox.Text.Length;
textBox.TextChanged -= TextBox_TextChanged;
textBox.Text = textBox.Text.Substring(0, textChange.Offset) + textBox.Text.Substring(textChange.Offset + textChange.AddedLength);
textBox.TextChanged += TextBox_TextChanged;
textBox.CaretIndex = caret - Math.Abs(textBox.Text.Length - length);
}
}
}
}

关于c# - 在不影响光标位置的情况下将 TextBox 输入限制为特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com