从 Sitecore 项目中删除渲染

Remove Rendering from Sitecore Item

我必须通过渲染 ID 删除渲染的所有实例。我尝试了以下代码,但它不起作用。

LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());

//Create a RenderingDefinition and add the reference of sublayout or rendering
RenderingDefinition renderingDefinition = new RenderingDefinition();
renderingDefinition.ItemID = sublayoutId;

var d = layoutDefinition.GetDevice(deviceDefinition.ID.ToString());
d.Renderings.Remove(renderingDefinition);

item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
item.Editing.EndEdit();

我提到了:

试试下面的代码。我还没有测试过它,但不是创建一个 RenderingDefinition 对象并将其从列表中删除(这不起作用,因为它不是对象的同一个实例),而是过滤现有的渲染数组比较 ItemId 属性:

LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());

var d = layoutDefinition.GetDevice(deviceDefinition.ID.ToString());

IEnumerable<RenderingDefinition> renderingsArray = d.Renderings.ToArray().Cast<RenderingDefinition>();
d.Renderings = new ArrayList(renderingsArray.Where(r => r.ItemID != sublayoutId).ToList());

item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
item.Editing.EndEdit();