Saving Items

I’ve tied the Clicked event of Save Item to a method in the AddItemPage XAML page’s code behind called OnSaveClicked.

<ContentPage.ToolbarItems>
	<ToolbarItem x:Name="saveItem"
		Name="Save"
		Clicked="OnSaveClicked"/>
</ContentPage.ToolbarItems>

The AddItemPage code behind page has a boolean field called addToBuyList.

private bool addToBuyList;

This addToBuyList boolean is used to determine which list to add the new item to based on the destination switch selection.

void OnDestinationSwitchToggled(object sender, EventArgs args)
{
	if (destinationSwitch.IsToggled == true) {
		destinationLabel.Text = "Save to Add list";
		addToBuyList = false;
	} else {
		destinationLabel.Text = "Save to Buy list";
		addToBuyList = true;
	}
}

The OnSaveClicked method in the AddItemPage code behind handles the Save Item tap. The new item is added to the allItems list that’s stored in the application’s Properties dictionary. Then, based on addToBuyList’s value, a message is sent to update the correct screen with the new item.

void OnSaveClicked(object sender, EventArgs args)
{
	if (Application.Current.Properties.ContainsKey("Items")) {
		List<Item> allItems = (List<Item>)Application.Current.Properties["Items"];
		allItems.Add(new Item(itemEntry.Text, addToBuyList));
		itemEntry.Text = "";
	}

	if (!addToBuyList) MessagingCenter.Send<AddItemPage>(this, "UpdateAddItemsListFromAddItems");
	else MessagingCenter.Send<AddItemPage>(this, "UpdateBuyItemsListFromAddItems");
}

New message subscribers were added to the Buy and Add pages. For BuyPage the new message calls an existing method but for AddPage I duplicated an existing method but gave it a new name for clarity.

// Buy Page
MessagingCenter.Subscribe<AddPage>(this, "UpdateBuyItemsList", (sender) => UpdateBuyItemsList());
MessagingCenter.Subscribe<AddItemPage>(this, "UpdateBuyItemsListFromAddItems", (sender) => UpdateBuyItemsList());

// Add Page
MessagingCenter.Subscribe<BuyPage>(this, "UpdateAddItemsListFromBuyList", (sender) => UpdateAddItemsListFromBuyList());
MessagingCenter.Subscribe<AddItemPage>(this, "UpdateAddItemsListFromAddItems", (sender) => UpdateAddItemsListFromAddItems());

I still have to implement some code in the AddItemPage’s code behind to prevent adding a duplicate item.

This entry was posted in Side Projects, Software Development and tagged , , , , . Bookmark the permalink.