dotnet / dotnet/wpf

Exception when showing MessageBox inside TextChanged of a custom TextBox control

Open
#11,140 0 comments 1 reaction 0 assignees View on GitHub
Investigate
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

### Description

When creating a custom control based on TextBox, an exception is thrown if a MessageBox.Show call is placed directly inside the TextChanged event.

However, when using the default WPF TextBox, the same code runs normally without any exception.

This behavior seems inconsistent between the default WPF TextBox and a custom TextBox control.

### Reproduction Steps

**1. Create a custom control derived from `TextBox`:**

```

public class CustomText : TextBox
{
//Override the template or add event handling for TextChanged.

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
//Code
}
}
```
***
**In Project Using Custom Control**
***
```
public partial class LoginWindow : Window
{
public LoginWindow()
{
txt.Text = "KOKO";
}

//System.InvalidOperationException: 'Dispatcher processing has been suspended, but messages are still being processed.'

private void txt_TextChanged(object sender, TextChangedEventArgs e)
{
MessageBox.Show($"{txt.Text} ");

}

}
```

### Expected behavior

The MessageBox should display normally, as it does when using the default WPF TextBox.

### Actual behavior

An exception is thrown when using a custom control.
No exception occurs when using the built-in WPF TextBox.

### Regression?

_No response_

### Known Workarounds

```
private void txt_TextChanged(object sender, TextChangedEventArgs e)
{

Dispatcher.BeginInvoke(new Action(() =>
{
MessageBox.Show($"{txt.Text} ");
}), DispatcherPriority.Background);
}
```
Or

await Task.Delay(10);
MessageBox.Show($"{txt.Text}");

### Impact

_No response_

### Configuration

.NET version: [.NET 8.0]
OS: [Windows 10 x64]

### Other information

The proposed solution is not practical for avoiding the expiration.
I want to know the reasons and are there any solutions for directly recalling the messageBox?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.