您可能希望将“ValidateMatrixFunc”属性公开为一个事件。为什么?它与通常实施控制的方式更加一致。此外,事件允许您为单个事件拥有多个订阅者(事件处理程序)。虽然这可能不是典型的用例,但有时确实会发生。
我在下面描述了如何将其作为事件来实现:
我们将事件称为“ValidatingMatrix”。
然后你可以像这样编写你的 ASPX 标记:
<uc1:MatrixTable ID="ucMatrixTable" runat="server" OnValidatingMatrix="ValidateMatrix" />
另外,让我们使用CancelEventHandler
委托而不是Func<bool>
. 这意味着您的代码隐藏中的 ValidateMatrix 方法签名必须如下所示:
protected void ValidateMatrix(object sender, System.ComponentModel.CancelEventArgs e)
{
// perform validation logic
if (validationFailed)
{
e.Cancel = true;
}
}
在 MatrixTable 自定义控件内部,实现如下内容:
const string ValidatingMatrixEventKey = "ValidatingMatrix";
public event System.ComponentModel.CancelEventHandler ValidatingMatrix
{
add { this.Events.AddHandler(ValidatingMatrixEventKey, value); }
remove { this.Events.RemoveHandler(ValidatingMatrixEventKey, value); }
}
protected bool OnValidatingMatrix()
{
var handler = this.Events[ValidatingMatrixEventKey] as System.ComponentModel.CancelEventHandler;
if (handler != null)
{
// prepare event args
var e = new System.ComponentModel.CancelEventArgs(false);
// call the event handlers (an event can have multiple event handlers)
handler(this, e);
// if any event handler changed the Cancel property to true, then validation failed (return false)
return !e.Cancel;
}
// there were no event handlers, so validation passes by default (return true)
return true;
}
private void MyLogic()
{
if (this.OnValidatingMatrix())
{
// validation passed
}
else
{
// validation failed
}
}