Mushriq Mushriq - 1 year ago 134
C# Question

UWP: Binding + TextChanging = JIT win32 exception

I am 100% sure I am doing this the wrong way and this problem is "by design".

I want to have a Slider and a TextBox that displays its value. The user can either use the Slider, or manually enter a number in the TextBox.

I also wanted to take advantage of the TextChanging event to ignore any non-numerical entries. TextChanged would only function after a user has entered something and it's not a preferable scenario, and KeyDown would not capture other methods of input like ink or speech.

So I have this:

<Slider x:Name="Size" Value="100" Maximum="100" Minimum="0" />
<TextBox x:Name="SizeText" Text="{Binding ElementName=Size,Path=Value,Mode=TwoWay}" TextChanging="SizeText_TextChanging" />

Where "SizeText_TextChanging" is simply an empty block of code right now:

private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
// Nothing Here.

This code builds, but at startup the app throws a JIT unhandled win32 exception and closes.

Changing TextChanging to TextChanged works fine, but again I prefer to get TextChanging to work (or something similar) to give a better user experience.

"Mode" also has no effect. I tried all three different Modes, all crash. By removing the binding altogether and giving the Text property any value works fine.

I also thought that maybe having the TextChanging event handler empty is the problem, so I borrowed the code below from here but the app still crashes:

private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
if (!Regex.IsMatch(sender.Text, "^\\d*\\.?\\d*$") && sender.Text != "")
int pos = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(pos, 1);
sender.SelectionStart = pos;

Like I said, I am probably approaching this the wrong way. I am just starting to learn UWP and C# so I am a total noob. But I have read everything I could about TextChanging and it simply talks about rendering the value and the associated cautions of what not to write within the TextChanging event. So while it sounds like the app is being thrown into a loop trying to read the value of the slider and trying to see what the TextChanging event says, I don't see how to fix it. Please help!

Thank you

Answer Source

I don't know why this is happening, but a workaround is to register the TextChanging event handler only once SizeText (or the page) has loaded and using x:Bind instead of Binding:


<TextBox x:Name="SizeText" Text="{x:Bind Size.Value, Mode=TwoWay}" Loaded="SizeText_Loaded"/>


private void SizeText_Loaded(object sender, RoutedEventArgs e)
    SizeText.TextChanging += SizeText_TextChanging;

private void SizeText_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download