我发现块块属性设置器在块“生命周期”期间只被调用一次。如果来自内部呼叫
SetDefaultValues(ContentType contentType)
我对此进行了一些测试:
1.创建新块
[ContentType(DisplayName = "SetterTestsBlock", GUID = "43ca7e93-6982-4b95-b073-c42af6ad2315", Description = "")]
public class SetterTestsBlock : BlockData
{
public virtual string SomeVirtualStringProperty
{
get => this.GetPropertyValue(t => t.SomeVirtualStringProperty);
set { this.SetPropertyValue(t => t.SomeVirtualStringProperty, "Ahoj1"); }
}
public string SomeStringProperty
{
get => this.GetPropertyValue(t => t.SomeStringProperty);
set { this.SetPropertyValue(t => t.SomeStringProperty, "Ahoj2"); }
}
public override void SetDefaultValues(ContentType contentType)
{
SomeVirtualStringProperty = "Čau1";
SomeStringProperty = "Čau2";
}
}
结果是可以预料的:
2.再次创建新块
[ContentType(DisplayName = "SetterTestsBlock", GUID = "43ca7e93-6982-4b95-b073-c42af6ad2315", Description = "")]
public class SetterTestsBlock : BlockData
{
public virtual string SomeVirtualStringProperty
{
get => this.GetPropertyValue(t => t.SomeVirtualStringProperty);
//set { this.SetPropertyValue(t => t.SomeVirtualStringProperty, "Ahoj1"); }
//set { }
set { throw new Exception(); }
}
public string SomeStringProperty
{
get => this.GetPropertyValue(t => t.SomeStringProperty);
//set { this.SetPropertyValue(t => t.SomeStringProperty, "Ahoj2"); }
//set { }
set { throw new Exception(); }
}
//public override void SetDefaultValues(ContentType contentType)
//{
// SomeVirtualStringProperty = "Čau1";
// SomeStringProperty = "Čau2";
//}
}
这次结果也是可以预料的:
3.发布更改以阻止测试2
这个结果不是那么令人期待:
测试结论:
问题
想象下面的代码所示的情况。
[ContentType(DisplayName = "RealUsageSimulation", GUID = "12737925-ab51-4f63-9144-cd4632244a1c", Description = "")]
public class RealUsageSimulation : BlockData
{
public string SomeStrPropWithDependency
{
get => this.GetPropertyValue(t => t.SomeStrPropWithDependency);
set
{
this.SetPropertyValue(t => t.SomeStrPropWithDependency, GetDBValue());
string GetDBValue()
{
return string.Join(
",",
value.Split(new[] { ',', ';', '/'}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()));
}
}
}
}
由于测试中描述的问题,这段代码没用。
我错了吗?如何以一种良好的方式解决这个问题?
(我知道解决方案。我只是想知道细节,提示。)
例如,通过在编辑模式下编辑来保存内容时,属性值不会通过模型类的属性保存(请记住:即使从代码中删除了内容类型类,也可以保存内容)。
在SetDefaultValues
中调用setter的原因是因为你的代码使用了class属性。
对于您的情况,可能更适合连接ContentSaving
事件以在保存内容时更改任何属性值。