wpf 在进入/离开数据网格文本框时检测是否使用默认值填充空白单元格

enxuqcxy  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(123)

根据从文件填充的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();

}
}
6pp0gazn

6pp0gazn1#

TouchLeave替换为LostFocus="UIElement_OnLostFocus"

private void UIElement_OnLostFocus(object sender, RoutedEventArgs e)
{
    if (sender is TextBox tb && string.IsNullOrEmpty(tb.Text))
    {
        tb.Text = "0";
    }
}

相关问题