根据从文件填充的datagrid数据模板文本框值,我想限制最终用户输入带"点"的整数,但我不想最终用户将单元格值保留为空白/空单元格,相反,我想将默认值设置为0,我使用了TextChanged & TouchLeave事件,但它不起作用。
什么是错误&我该如何解决这个问题?我应该使用哪个事件?谢谢
XAML:
<DataGridTemplateColumn Header="Price" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Price}" PreviewTextInput="OnPreviewTextInput"
PreviewKeyDown="TextBox_PreviewKeyDown"
TextChanged="TextBox_TextChanged" TouchLeave="TextBox_TouchLeave" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
代码:
private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
string CultureName = Thread.CurrentThread.CurrentCulture.Name;
CultureInfo ci = new CultureInfo(CultureName);
ci.NumberFormat.NumberDecimalSeparator = ".";
Thread.CurrentThread.CurrentCulture = ci;
//Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator
string input = ((TextBox)sender).Text + e.Text;
string pattern = "^[0-9]+[" + ci.NumberFormat.NumberDecimalSeparator + "]?([0-9]+)?$";
Regex regex = new Regex(pattern);
e.Handled = !regex.IsMatch(input);
}
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
// Prohibit space
if (e.Key == Key.Space)
e.Handled = true;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(e.ToString()))
{
e.Handled = true;
((TextBox)sender).Text = 0.ToString();
}
}
private void TextBox_TouchLeave(object sender, TouchEventArgs e)
{
if (string.IsNullOrEmpty(e.ToString()))
{
e.Handled = true;
((TextBox)sender).Text = 0.ToString();
}
}
1条答案
按热度按时间6pp0gazn1#
将
TouchLeave
替换为LostFocus="UIElement_OnLostFocus"