0

By default, a WPF TextBox binding sets a string property to an empty string if you first enter some text and then clear it again. I understand the logic for this choice but this means that the database can contain both NULL and empty string values for these fields.

It would be good practice to always check for NULL and empty string when retrieving and using these values, but I want to tackle the problem at the core.

There are several solutions: WPF Converters, convert empty strings to NULL in the business layer or using TargetNullValue:

<TextBox Text="{Binding Value, TargetNullValue=''}"/>

Unfortunately, these solutions need to be implemented for individual properties and TextBoxes.

Is there a way to make all TextBoxes convert empty strings to NULL values?

Bruno V
  • 1,721
  • 1
  • 14
  • 32
  • 1
    You could write your own Custom Binding Extension and use that for your `TextBoxes`. Have a look at [this article](http://www.c-sharpcorner.com/uploadfile/mamta_m/creating-a-custom-markup-extension-in-wpf/) for more info. – XAMlMAX Dec 22 '17 at 11:35
  • You could also create a custom `TextBox` control that derives from `TextBox` and overwrite the `Text` property that will return null when string.IsNullOrEmpty returns true. – XAMlMAX Dec 22 '17 at 15:06
  • Try with this: https://stackoverflow.com/a/15567948/8507673 in your app.xaml – sTrenat Dec 22 '17 at 18:20
  • @XAMlMAX: thank you for the suggestions. Both solutions however need refactoring of all existing `TextBoxes` and all future development must use the new syntax. I was hoping for a solution that could be applied globally as @sTrenat suggests, but a `TextBox.Text` property cannot be compared to null. It's always a string or empty string. – Bruno V Jan 03 '18 at 14:15

1 Answers1

1

What about a Global ClassHandler? Everytime a TextBox loses Focus, check if it is an empty string.

Add the following to the OnStartup Method in your App.xaml.cs

EventManager.RegisterClassHandler(typeof(TextBox), TextBox.LostFocusEvent, new RoutedEventHandler((s, a) =>
{
    if((s as TextBox).Text == "")
        (s as TextBox).Text = null;
}));
bergerb
  • 71
  • 7
  • This does not provide an answer to the question. You can [search for similar questions](/search), or refer to the related and linked questions on the right-hand side of the page to find an answer. If you have a related but different question, [ask a new question](/questions/ask), and include a link to this one to help provide context. See: [Ask questions, get answers, no distractions](/tour) – STA Mar 11 '21 at 11:00
  • I disagree, I think does possibly answer the question posed or point the user in the right direction. If the TextChanged event is accessible from RegisterClassHandler then it could be used to fit the use case. – b.pell Mar 11 '21 at 12:50