Home > Software engineering >  Detect blank cell fill with default value on enter/leave datagrid textbox
Detect blank cell fill with default value on enter/leave datagrid textbox

Time:12-21

From my datagrid data template textbox value filled from a file, i want to restrict the end user to enter integer with 'dot' but i dont want the end user to leave the cell value as a blank/empty cell, instead i want to put default value as 0, i used TextChanged & TouchLeave events but its not working.

What is the mistake & how can i fix this? which event i should use? thanks

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>

code:

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();

}
}

CodePudding user response:

Instead of TouchLeave add LostFocus="UIElement_OnLostFocus"

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