Continuing from: Why will it always be a null value?
When I PageStyle.GetInstance().StartItem = MyWantedStartItem; StartItem within the instance remains null and doesn’t get updated, making my class unusable. This in turn returns a item cannot be null error.
Again I want to know why this is happening, What can I do to resolve it? And is there a better way of doing this?
The class accessing the object:
public partial class MainLayout : System.Web.UI.Page
{
public string StartItem;
protected void Page_Load(object sender, EventArgs e)
{
GetStartItem();
SetStartItem();
InitializeCSS();
}
private void GetStartItem()
{
StartItem = Sitecore.Context.Item.Paths.FullPath;
}
private void SetStartItem()
{
PageStyle.GetInstance().StartItem = StartItem;
}
private void InitializeCSS()
{
Body.Attributes.Add("style", "background-color: " + PageStyle.GetInstance().BackgroundColor); // Body background color
}
}
The class being accessed has:
private static PageStyle _Instance = null;
// Instantiate variables relating to sitecore item paths.
Database webDB;
Sitecore.Data.Items.Item item;
private string _startItem;
public string StartItem
{
get
{
return _startItem;
}
set
{
_startItem = value;
}
}
// constructor
private PageStyle()
{
this.webDB = Sitecore.Configuration.Factory.GetDatabase("web");
this.item = webDB.Items[StartItem];
}
// Method that gets instance
public static PageStyle GetInstance()
{
if (_Instance == null)
_Instance = new PageStyle();
return _Instance;
}
Resolved by doing this:
Then when ever I need the instance I define the start item i am going to use.
PageStyle.GetInstance(MyItem);Which will set it and get me the desired affect.