WPF DataBinding监视抛出异常 [英] WPF DataBinding watch for thrown exceptions
问题描述
在WPF中,当我将一个属性绑定到一个控件,如文本框,当该值改变时,我不知道如何处理异常并显示错误消息。
示例:
public string ConnectionString
{
get
{
return(_ConnectionString);
}
set
{
try
{
_ConnectionString = value;
_SqlConnection = new System.Data.SqlClient.SqlConnection(_ConnectionString);
_ConnectionTested = true;
}
catch(异常捕获)
{
_ConnectionTested = false;
_TableNameTested = false;
_FieldNameTested = false;
_ConditionTested = false;
_ConnectionString =;
// ----删除值----
ValuesCollection.Clear();
throw(new Exception(Can not Open the connection String \\\
Reason:+ caught.Message));
}
}
}
,而wpf部分就像:
< TextBox TextWrapping =Wrapx:Name =ConnectionStringTextBoxText ={Binding Path = ConnectionString,Mode = TwoWay}/>
无论如何,当文本框中的值更改时检查模型是否抛出异常,然后显示用户的exception.message?
谢谢
请查看绑定验证。 绑定
类有一个 ValidationRules
集合,您可以向其中添加一个 ExceptionValidationRule
。
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
Take a look at binding validation. The Binding
class has a ValidationRules
collection, to which you can add an ExceptionValidationRule
.
这篇关于WPF DataBinding监视抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!