My fourteenth How do I is up.
Scenario
Let's say that we want to cancel an editing operation in a model element property if the new value meets a certain condition. The focus of this How do I tackles this scenario.
In the next sample we have a MyLanguage dsl and a MyElement domain class and we want to cancel the editing operation over the "Foo" property if the new value is empty.
Interfaces and classes needed
Code snippet
public partial class MyLanguageDomainModel
{
protected override Type[] GetCustomDomainModelTypes()
{
var types = new List<Type>();
types.AddRange(base.GetCustomDomainModelTypes());
types.Add(typeof(MyElementChangeRule));
return types.ToArray();
}
}
[RuleOn(typeof(MyElement), FireTime = TimeToFire.TopLevelCommit)]
public partial class MyElementChangeRule : ChangeRule
{
public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
{
if(!e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing)
{
if(e.DomainProperty.Name.Equals("Foo"))
{
if(string.IsNullOrEmpty(e.NewValue.ToString()))
{
//The name cannot be empty, therefore we cancel the change
PackageUtility.ShowError(e.ModelElement.Store, "Value cannot be empty");
e.ModelElement.Store.TransactionManager.CurrentTransaction.Rollback();
}
}
}
}
}
Assemblies needed
- Microsoft.VisualStudio.Modeling.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Stay tuned,
Pablo