商信互联
本主题描述如何限制最终用户可以使用“新建 操作”创建的对象数。假设您正在使用“业务类库”中的“任务”业务类。使用“新操作”创建新任务时,将检查现有任务对象的数量,并且如果已经存在三个对象,则将不允许最终用户创建其他对象。
移动平台不支持本主题中描述的方法。
DevExpress代码示例数据库(http://www.devexpress.com/example=E239)中提供了完整的示例项目。
接取任务列表查看时,新的行动是要创建一个新的对象,处理NewObjectViewController.ObjectCreating的事件NewObjectViewController,其中包含了新的行动。为此,实现一个新的View Controller并以以下方式覆盖OnActivated方法。
using DevExpress.ExpressApp;
using DevExpress.Persistent.BaseImpl;
using DevExpress.ExpressApp.SystemModule;
//...
public class LimitTaskAmountController : ViewController {
private NewObjectViewController controller;
protected override void OnActivated() {
base.OnActivated();
controller = Frame.GetController<NewObjectViewController>();
if (controller != null) {
controller.ObjectCreating = controller_ObjectCreating;
}
}
void controller_ObjectCreating(object sender, ObjectCreatingEventArgs e) {
if ((e.ObjectType == typeof(Task)) &&
(e.ObjectSpace.GetObjectsCount(typeof(Task), null) >= 3)) {
e.Cancel = true;
throw new UserFriendlyException(
"Cannot create a task. Maximum allowed task count exceeded.");
}
}
protected override void OnDeactivated() {
if (controller != null) {
controller.ObjectCreating -= controller_ObjectCreating;
}
base.OnDeactivated();
}
}
Imports DevExpress.ExpressApp
Imports DevExpress.Persistent.BaseImpl
Imports DevExpress.ExpressApp.SystemModule
'...
Public Class LimitTaskAmountController
Inherits ViewController
Private controller As NewObjectViewController
Protected Overrides Sub OnActivated()
MyBase.OnActivated()
controller = Frame.GetController(Of NewObjectViewController)()
If controller IsNot Nothing Then
AddHandler controller.ObjectCreating, AddressOf controller_ObjectCreating
End If
End Sub
Private Sub controller_ObjectCreating(ByVal sender As Object, ByVal e As ObjectCreatingEventArgs)
If (e.ObjectType Is GetType(Task)) AndAlso (e.ObjectSpace.GetObjectsCount(GetType(Task), Nothing) >= 3) Then
e.Cancel = True
Throw New UserFriendlyException("Cannot create a task. Maximum allowed task count exceeded.")
End If
End Sub
Protected Overrides Sub OnDeactivated()
If controller IsNot Nothing Then
RemoveHandler controller.ObjectCreating, AddressOf controller_ObjectCreating
End If
MyBase.OnDeactivated()
End Sub
End Class
您可以禁用某个动作,而不要中断其执行。请参阅“如何:在当前视图具有未保存的更改时禁用操作”示例。