这对我有用,但想知道它是正确的方法还是有更好的方法来显示一个被设置为子布局的数据源的项目。
sample.ascx
<sc:Text ID="txtHeader" runat="server" Field="Header" />
<br/>
<sc:Image ID="imgMotif" runat="server" Field="Motif Left" />
<br/>
<!-- some more controls -->
sample.ascx.cs
private void BindData()
{
Item introItem = GetItemFromDatasource((Sublayout)this.Parent);
if(introItem != null)
{
txtHeader.Item = introItem;
imgMotif.Item = introItem;
//..and so on..
}
}
private Item GetItemFromDatasource(Sublayout sublayout)
{
Item dataSource = null;
if (sublayout != null)
{
Guid dataSourceId;
if (Guid.TryParse(sublayout.DataSource, out dataSourceId))
dataSource = Sitecore.Context.Database.GetItem(new ID(dataSourceId));
}
return dataSource;
}
答案 0 :(得分:1)
我建议您的子布局从子布局基础继承。
您的SublayoutBase将如下所示:
public class SublayoutBase : UserControl
{
private Item _dataSource;
public Item DataSource
{
get
{
if (_dataSource == null)
{
if (Parent is Sublayout)
{
var sublayout = (Sitecore.Web.UI.WebControls.Sublayout)Parent;
Guid dataSourceId;
if (Guid.TryParse(sublayout.DataSource, out dataSourceId))
{
_dataSource = Sitecore.Context.Database.GetItem(new ID(dataSourceId));
}
else
{
_dataSource = Sitecore.Context.Database.GetItem(sublayout.DataSource);
}
}
if (_dataSource == null)
{
_dataSource = Sitecore.Context.Item;
}
}
return _dataSource;
}
}