2014-02-26 40 views

回答

1

您可以创建一个事件处理程序,在创建新节点时更改节点的排序顺序。有关实现您自己的处理程序的更多详细信息,请参见Application startup events & event registration

粗糙未经测试的例子,我相信你可以做更多的优雅,但应该指向你在正确的方向:

public class YourApplicationEventHandlerClassName : ApplicationEventHandler 
{ 
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) 
    { 
     ContentService.Created += ContentServiceCreated; 
    } 

    private void ContentServiceCreated(IContentService sender, NewEventArgs<IContent> e) 
    { 
     var cs = ApplicationContext.Current.Services.ContentService; 
     var content = e.Entity; 
     var parentNode = content.Parent(); 

     content.SortOrder = parentNode.Children().OrderBy(n => n.SortOrder).First().SortOrder - 1; 
     cs.Save(content); 
    } 
} 
+0

除上面的例子你最好先检查父节点是否有子节点,否则你会得到一个空引用异常。 – ProNotion

+0

谢谢你。但是什么时候该函数会被执行?我没有在您提供的链接的任何地方看到ContentServiceCreated? – Aximili

+0

您不会在文档中找到它,因为EventHandlers的实现取决于您,您以与其他任何事件相同的方式订阅它们。我用更完整的例子更新了我的答案。如事件名称所示,在创建ANY节点时执行。 – ProNotion

1

ContentService.Created事件并没有为我工作。采取了一些战斗,但在Umbracov7,我已经使用了ContentService.Saved事件代替,用脏性能有一定的双重检查,以确保您在节省无限循环不结束:

private void ContentSaved(IContentService sender, SaveEventArgs<IContent> e) 
    { 
     foreach (var content in e.SavedEntities) 
     { 
      var dirty = (IRememberBeingDirty)content; 
      var isNew = dirty.WasPropertyDirty("Id"); 
      if (!isNew) return; 

      var parentNode = content.Parent(); 
      if (parentNode == null) return; 
      var last = parentNode.Children().OrderBy(n => n.SortOrder).FirstOrDefault(); 
      if (last != null) 
      { 
       content.SortOrder = last.SortOrder - 1; 
       if (content.Published) 
        sender.SaveAndPublishWithStatus(content); 
       else 
        sender.Save(content); 
      } 
     } 
    } 

public class AppStartupHandler : ApplicationEventHandler 
{ 
    protected override void ApplicationInitialized(UmbracoApplicationBase umbracoApplication, 
     ApplicationContext applicationContext) 
    { 
     ContentService.Saved += ContentSaved; 
    } 
}