Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6174073
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T23:41:25+00:00 2026-05-23T23:41:25+00:00

My problem: I would like to validate the user input of a TextBox using

  • 0

My problem: I would like to validate the user input of a TextBox using the control’s ValidatesOnExceptions property.

XAML code:

DataContext="{Binding RelativeSource={RelativeSource Self}}"       
...
<TextBox x:Name="TestTextBox" Text="{Binding TestText, Mode=TwoWay, ValidatesOnExceptions=True}" TextChanged="TestTextBox_TextChanged"/>

1 : The validation using a normal property works fine:

ViewModel code:

private string _testText, 

public string TestText {
    get {return _testText;} 
    set { 
        if (value=="!")
            throw new Exception("Error: No ! allowed!");
        _testText = value;
    }
}

2: The validation using a Dependency Property causes “A first chance exception of type ‘System.Exception’…” and the application stops working.

ViewModel code:

public partial class MyControl : UserControl {
    public MyControl() {
        InitializeComponent();
    }

    public static readonly DependencyProperty TestTextProperty = DependencyProperty.Register("TestText", typeof(String), typeof(MyControl), new PropertyMetadata("DefaultText", new PropertyChangedCallback(OnTestTextChanged)));

    public event TextChangedEventHandler TestTextChanged;

    public String TestText {
        get {
            return (String)GetValue(TestTextProperty);
        }
        set {
            SetValue(TestTextProperty, value);

            if (TestTextChanged != null) {
                TestTextChanged(TestTextBox, null);
            }

            if (TestText=="!") {
                throw new Exception("No ! allowed!");
            }
        }
    }

    static void OnTestTextChanged(object sender, DependencyPropertyChangedEventArgs args) {
        MyControl source = (MyControl)sender;
        source.TestTextBox.Text = (String)args.NewValue;
    }

    private void TestTextBox_TextChanged(object sender, TextChangedEventArgs e) {
        TextBox source = (TextBox)sender;
        TestText = source.Text;
    }
}

What am I doing wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T23:41:26+00:00Added an answer on May 23, 2026 at 11:41 pm

    If you run your second example and take a look at the call stack when the exception gets thrown, you’ll see that it’s not going through the dependency system at all. The textbox’s text changed, the event handler runs and that encountered an exception. That’s why the application dies.


    I suspect you put that TextChanged event handler in because your OnTestTextChanged method wasn’t being called. As it happens, there’s a reason for this, but it’s a bit subtle and I can’t find any documentation to back it up. I refer to this behaviour as ‘blacklisting’. In short, if you have a PropertyChangedCallback on a dependency property, and the PropertyChangedCallback causes the same dependency property to be set, either directly or indirectly, the PropertyChangedCallback gets ‘blacklisted’ and never gets called again.

    Your PropertyChangedCallback is as follows:

    static void OnTestTextChanged(object sender, DependencyPropertyChangedEventArgs args) {
        MyControl source = (MyControl)sender;
        source.TestTextBox.Text = (String)args.NewValue; // *******
    }
    

    The asterisked line is the problem here. What happens is as follows:

    • you set the Text property of the TextBox,
    • Silverlight then updates the value of your TestText dependency property using the binding,
    • this would cause another call into your PropertyChangedCallback.

    However, at this point Silverlight realises that it is making a recursive call to your PropertyChangedCallback, and instead of calling it again, decides to ‘blacklist’ it. As a result of this ‘blacklisting’, your PropertyChangedCallback never gets called again. Annoyingly, there’s no error or warning when it does this.

    I’m not sure why it doesn’t give any warnings or errors. However, if it didn’t ‘blacklist’ your PropertyChangedCallback and continued to call it, you’d end up with a stack overflow.

    So, how do you fix your code? Well, to start with, I’d like to introduce a golden rule of working with Silverlight (and WPF) dependency properties, which your code violates:

    THE SETTER IN THE PROPERTY BACKED BY THE DEPENDENCY PROPERTY SHOULD CALL SetValue AND DO NOTHING MORE. Anything you want to do whenever the value of the dependency property changes must go in a PropertyChangedCallback and NOT in the property setter.

    If you don’t stick to this rule, you are entering a world of pain.

    Your TestText property should therefore look like the following:

        public String TestText
        {
            get { return (String)GetValue(TestTextProperty); }
            set { SetValue(TestTextProperty, value); }
        }
    

    and instead you should do the validation in your PropertyChangedCallback:

        static void OnTestTextChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            if ((string)args.NewValue == "!")
            {
                throw new Exception("No ! allowed!");
            }
        }
    

    After making these changes to your code, I was able to run it and get a validation tooltip to show on the TextBox when I entered the text !.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a problem and i would like to learn the correct way to
I have a problem that I would like have solved via a SQL query.
Problem Language: C# 2.0 or later I would like to register context handlers to
I have seen this problem arise in many different circumstances and would like to
I am facing a problem. I would like to localize my action names in
i have a weird problem. i would like to delete an assembly(plugin.dll on harddisk)
As popular as Ruby and Rails are, it seems like this problem would already
I have an interesting problem and would appreciate your thoughts for the best solution.
Ok here's a little problem I would love to get some help on. I
If I have the following code: class User < ActiveRecord::Base has_many :problems attr_accessible :email,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.