WPF DataBinding watch for thrown exceptions

 

Questions


In my model I have lots of properties for different objects and I’m checking the value while setting value for object and if the value is not accepted I will throw an exception this was working perfect with windows forms propertygrid but now I’m trying to design a new interface using WPF .
in WPF when I bound a property to a control like textbox ,when the value is changed I don’t know how to handle the exception and show the error message .
example :

public string  ConnectionString
        {
            get
            {
                return (_ConnectionString);
            }
            set
            {
                try
                {
                    _ConnectionString  = value ;
                    _SqlConnection = new System.Data.SqlClient.SqlConnection(_ConnectionString);
                    _ConnectionTested = true;
                }
                catch (Exception caught)
                {
                    _ConnectionTested = false;
                    _TableNameTested = false;
                    _FieldNameTested = false;
                    _ConditionTested = false;
                    _ConnectionString = "";
                    //----delete values----
                    ValuesCollection.Clear();
                    throw (new Exception("Can not Open the connection String nReason : " + caught.Message )); 
                }
            }
        }

and the wpf part is like :

<TextBox TextWrapping="Wrap" x:Name="ConnectionStringTextBox" Text="{Binding Path=ConnectionString, Mode=TwoWay}"/>

is there anyway when the value in textbox is changed check if the model has thrown an exception and then show the exception.message to user ?

thanks

 

 

————————————————-

Answer

Take a look at binding validation. The Binding class has a ValidationRules collection, to which you can add an ExceptionValidationRule.

c#,data-binding,exception-handling,wpf

Facebook Comments

Post a comment