Freigeben über


Stackoverflow, TextBox, UpdateSourceTrigger, PropertyChanged, RelativeSource Self

For lack of a better title, I am sure someone out there tried to perform validation work on a textbox where it was bound to itself.  Follow the code sample if you will:

<TextBox>
    <TextBox.Text>
      <Binding RelativeSource="{RelativeSource Self}" Path="Text" UpdateSourceTrigger="PropertyChanged" />
    </TextBox.Text>
</TextBox>

Once you type something in the text box, whammo!  StackOverflowException.  See: https://forums.msdn.microsoft.com/en-us/wpf/thread/bf300eea-5856-4738-b565-b8e2f5e52195/ for reasons why.

Workaround:
The easiest way to get around this is to set the UpdateSourceTrigger to "LostFocus,"  the default setting.  However, this leads into some hackery causing you to force validation by focusing on the control property. 

textBox1.Focus();
someOtherControl.Focus();

If you really want a validation on every character entered, you can approach this is by creating a private string dependancy property, and using a border to simulate the red outlining.

public static readonly DependencyProperty MyStringProperty = DependencyProperty.Register(
     "MyString",
      typeof(String),
     typeof(Window1));

public String MyString
{
     get { return (String ).GetValue(Window1.MyStringProperty ); }
     set { SetValue(Window1.MyStringProperty , value); }
}

public Window1()
{
InitializeComponent();
     textBox1.TextChanged += delegate(object sender, RoutedEventArgs e)
{
          if (Valid())
{
border.BorderBrush = null;
}
else
{
border.BorderBrush = Brushes.Red;
}
};
}

<

Border>
<TextBox>
     </TextBox>
</Border>

Comments