TextBox.TextChanged event firing twice on Windows

2019-03-08 09:28发布

I have a very simple test app just to play around with Windows Phone 7. I've just added a TextBox and a TextBlock to the standard UI template. The only custom code is the following:

public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private int counter = 0;

    private void TextBoxChanged(object sender, TextChangedEventArgs e)
    {
        textBlock1.Text += "Text changed " + (counter++) + "\r\n";
    }
}

The TextBox.TextChanged event is wired up to TextBoxChanged in the XAML:

<TextBox Height="72" HorizontalAlignment="Left" Margin="6,37,0,0"
         Name="textBox1" Text="" VerticalAlignment="Top"
         Width="460" TextChanged="TextBoxChanged" />

However, every time I press a key when running in the emulator (either the on-screen keyboard or the physical one, having pressed Pause to enable the latter) it increments the counter twice, displaying two lines in the TextBlock. Everything I've tried shows that the event is genuinely firing twice, and I've no idea why. I've verified that it's only being subscribed once - if I unsubscribe in the MainPage constructor, nothing happens at all (to the text block) when the text changes.

I've tried the equivalent code in a regular Silverlight app, and it didn't occur there. I don't have a physical phone to reproduce this with at the moment. I haven't found any record of this being a known problem in the Windows Phone 7.

Can anyone explain what I'm doing wrong, or should I report this as a bug?

EDIT: To reduce the possibility of this being down to having two text controls, I've tried removing the TextBlock completely, and changing the TextBoxChanged method to just increment counter. I've then run in the emulator, typed 10 letters and then put a breakpoint on the counter++; line (just to get rid of any possibility that breaking into the debugger is causing issues) - and it shows counter as 20.

EDIT: I've now asked in the Windows Phone 7 forum... we'll see what happens.

10条回答
时光不老,我们不散
2楼-- · 2019-03-08 09:36

That does sound like a bug to me. As a workaround, you could always use Rx's DistinctUntilChanged. There is an overload that allows you to specify the distinct key.

This extension method returns the observable TextChanged event but skips consecutive duplicates:

public static IObservable<IEvent<TextChangedEventArgs>> GetTextChanged(
    this TextBox tb)
{
    return Observable.FromEvent<TextChangedEventArgs>(
               h => textBox1.TextChanged += h, 
               h => textBox1.TextChanged -= h
           )
           .DistinctUntilChanged(t => t.Text);
}

Once the bug is fixed you can simply remove the DistinctUntilChanged line.

查看更多
干净又极端
3楼-- · 2019-03-08 09:36

Sure looks like a bug to me, if you're trying to raise an event every time the text changes you could try using a two-way binding instead, unfortunately this won't raise per-key press change events (only when the field loses focus). Here's a workaround if you need one:

        this.textBox1.TextChanged -= this.TextBoxChanged;
        textBlock1.Text += "Text changed " + (counter++) + "\r\n";
        this.textBox1.TextChanged += this.TextBoxChanged;
查看更多
ら.Afraid
4楼-- · 2019-03-08 09:36

It's an old topic, but instead of change template (that does not work for me, I dont't see the other textbox with Blend) you can add boolean to check if the event already did the function or not.

boolean already = false;
private void Tweet_SizeChanged(object sender, EventArgs e)
{
    if (!already)
    {
        already = true;
        ...
    }
    else
    {
    already = false;
    }
}

I'm aware that is NOT the perfect way, but I think it's the simple way to do that. And it works.

查看更多
Juvenile、少年°
5楼-- · 2019-03-08 09:43

The reason the TextChanged event fires twice in WP7 is a side effect of how the TextBox has been templated for the Metro look.

If you edit the TextBox template in Blend you will see that it contains a secondary TextBox for the disabled/read-only state. This causes, as a side effect, the event to fire twice.

You can change the template to remove the extra TextBox (and associated states) if you don't need these states, or modify the template to achieve a different look in the disabled/read-only state, without using a secondary TextBox.

With that, the event will fire only once.

查看更多
乱世女痞
6楼-- · 2019-03-08 09:47

I dont think it is a bug .. When you assign the value to a text property inside the textchanged event , the textbox value is changed which will again call the text changed event ..

try this in Windows Forms Application , you might get an error

"An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll"

查看更多
一夜七次
7楼-- · 2019-03-08 09:52

Nice! I found this question by searching for a related problem and also found this annoying thing in my code. Double event eats more CPU resources in my case. So, I fixed my real-time filter textbox with this solution:

private string filterText = String.Empty;

private void SearchBoxUpdated( object sender, TextChangedEventArgs e )
{
    if ( filterText != filterTextBox.Text )
    {
        // one call per change
        filterText = filterTextBox.Text;
        ...
    }

}
查看更多
登录 后发表回答