Items in a file are being read in a weird order on Xamarin iOS - file-io

I am reading a list of files in a folder in my Xamarin app and displaying them in a ListView. On Android, the files are created and read in the correct order, but on iOS, they are created in the right order, but read and displayed in a weird order and in the exact same weird order every time. I know it's not a problem with the ListView because I was using Syncfusion's SfListView recently and had the same problem with that. Why is it like this?
The correct order of the files:
What they look like on iOS:
My code to create the files:
using Partylist.Models;
using System;
using System.IO;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Partylist.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewEventPage : ContentPage
{
...
// Event handler for when the "Create" button gets clicked.
async void OnCreateClicked(object sender, EventArgs e)
{
// Make sure there is something in the text entry.
if (string.IsNullOrWhiteSpace(EventNameEntry.Text))
{
// If there is nothing there, display an error message.
await DisplayAlert("Oops!", "Your event needs a name!",
"OK");
}
// If there is something in the text entry, try to create
// a new event with the text as its name.
else
{
// Variable to store the created event.
Event newEvent = new Event();
// Variable to store its folder.
DirectoryInfo newEventFolder;
// Flag to see if the event was created sccessfully.
bool eventCreated;
try
{
// If there's already an event with that name, let the
// user know.
if (Directory.Exists(Path.Combine(App.eventFolderPath,
EventNameEntry.Text)))
{
await DisplayAlert("Oops!", "You already have an event with that name.", "Ok");
eventCreated = false;
}
// Otherwise, try to create the folder.
else
{
newEventFolder = Directory.CreateDirectory(
Path.Combine(App.eventFolderPath,
EventNameEntry.Text));
// Then, create the event based on that folder.
newEvent = new Event
{
EventFolder = newEventFolder,
Location = WhereEntry.Text,
EventDate = EventDatePicker.Date,
StartTime = EventStartTimePicker.Time,
EndTime = EventEndTimePicker.Time,
Refreshments = RefreshmentsEntry.Text,
Activities = ActivitiesEntry.Text,
NumGuests = NumGuestsEntry.Text,
Theme = ThemeEntry.Text,
Budget = BudgetEntry.Text,
WillThereBePartyFavors = PartyFavorsEntry.Text,
ShouldGuestsBringGifts = GiftsEntry.Text,
WillThereBeChildren = ChildrenEntry.Text
};
// --- Add several premade lists to the event (all of --- //
// --- which are empty except the main checklist) --- //
// First, the main checklist. Also, set it as such.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Main Checklist.mchec"))) { }
// Then, a contact list for important phone numbers.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Important Phone Numbers.cont"))) { }
// And another contact list for guests.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Guests.cont"))) { }
// The next thing we need is a schedule of activities.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Schedule of Activities.sched"))) { }
// After that, a checklist for things to do.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Things to Do.chec"))) { }
// And one for things to gather.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Things to Gather.chec"))) { }
// And one for things to buy.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Things to Buy.chec"))) { }
// And one for things to make.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Things to Make.chec"))) { }
// And one that serves as a grocery list.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"Groceries.chec"))) { }
// There will also be one for things to do the day before the event.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"The Day Before.chec"))) { }
// And one for things to do the day of.
using (FileStream fs = File.Create(Path.Combine(App
.eventFolderPath, EventNameEntry.Text,
"The Day Of.chec"))) { }
// --- End of adding pre-made lists --- //
// Let the program know that an event has been created.
eventCreated = true;
}
}
// Should throw an ArgumentException in most cases where there is
// an invalid character.
catch (ArgumentException)
{
// Get all the invalid characters and turn them into a string.
char[] invalidChars = Path.GetInvalidPathChars();
string invalid = "";
foreach(char currentChar in invalidChars)
{
invalid += currentChar;
}
// Display an error message.
await DisplayAlert("Oops!", "Your event name can't have these characters: \""
+ invalid + "\".", "Ok");
eventCreated = false;
}
// If the event was created successfully, start the tip
// timer, select the event, open a "List" page
// for it, and removed the "New Event" page.
if (eventCreated)
{
App.tipTimer.Start();
App.selectedEvent = newEvent;
await Navigation.PushAsync(new ListsPage());
Navigation.RemovePage(this);
}
}
}
}
}
And my code to read in the files:
using Partylist.Models;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Partylist.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListsPage : ContentPage
{
// List of lists, used to populate
// the page's ListView (see the XAML).
public ObservableCollection<PartylistList> ListList { get; set; }
...
// Override for OnAppearing().
protected override void OnAppearing()
{
// Regular OnAppearing() method.
base.OnAppearing();
// Set the title to be the name of the selected event.
Title = App.selectedEvent.EventFolder.Name;
// Set the BindingContext of the page to itself.
BindingContext = this;
// Update the ListView.
UpdateListView();
...
}
// Function to update the ListView when the page loads or when something changes.
private void UpdateListView()
{
// Set the list of lists to a new ObservableCollection
// that we can add stuff to.
ListList = new ObservableCollection<PartylistList>();
// Loop to populate the ObservableCollection.
for (int i = 0; i < Directory.GetFiles(
Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))
.Length; i++)
{
// If the current file is the main checklist (filename ends with ".mchec"),
// then add it to the list of lists as the main checklist.
if (Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i].EndsWith(".mchec"))
{
ListList.Add(new PartylistList(new FileInfo(Path.GetFullPath(
Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i])), new ChecklistPage(),
"#FF7700", "master_checklist_icon.png"));
// Set a "Rename" button as this thing's only SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Rename",
BackgroundColor = Color.FromHex("#ff7700"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[0].Invoked += OnRename;
// Set this as the event's main checklist.
App.selectedEvent.MainChecklist = new FileInfo(Path.GetFullPath(
Directory.GetFiles(Path.Combine(App.eventFolderPath, App
.selectedEvent.EventFolder.Name))[i]));
}
// If the current file is a contact list (filename ends with ".cont"),
// then add it to the list of lists as a contact list.
else if (Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i].EndsWith(".cont"))
{
ListList.Add(new PartylistList(new FileInfo(Path.GetFullPath(
Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i])), new ContactsListPage(),
"#00DFDF", "contact_list_icon.png"));
// Set a "Delete" button as the first SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Delete",
BackgroundColor = Color.FromHex("#ff418b"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[0].Invoked += OnDelete;
// Set a "Rename" button as the second SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Rename",
BackgroundColor = Color.FromHex("#ff7700"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[1].Invoked += OnRename;
}
// Else if it is a schedule (filename ends with ".sched"), then
// add it to the list of lists as a schedule.
else if (Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i].EndsWith(".sched"))
{
ListList.Add(new PartylistList(new FileInfo(Path.GetFullPath(
Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i])), new SchedulePage(),
"#BB0099", "schedule_icon.png"));
// Set a "Delete" button as the first SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Delete",
BackgroundColor = Color.FromHex("#ff418b"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[0].Invoked += OnDelete;
// Set a "Rename" button as the second SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Rename",
BackgroundColor = Color.FromHex("#ff7700"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[1].Invoked += OnRename;
}
// Else if it is a checklist (filename ends with ".chec"), then
// add it to the list of lists as a checklist.
else if (Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i].EndsWith(".chec"))
{
ListList.Add(new PartylistList(new FileInfo(Path.GetFullPath(
Directory.GetFiles(Path.Combine(App.eventFolderPath,
App.selectedEvent.EventFolder.Name))[i])), new ChecklistPage(),
"#3F7FFF", "checklist_icon.png"));
// Set a "Delete" button as the first SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Delete",
BackgroundColor = Color.FromHex("#ff418b"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[0].Invoked += OnDelete;
// Set a "Rename" button as the second SwipeItem.
ListList.ElementAt(i).SwipeOptions.Add(new SwipeItem()
{
Text = "Rename",
BackgroundColor = Color.FromHex("#ff7700"),
CommandParameter = ListList.ElementAt(i)
});
ListList.ElementAt(i).SwipeOptions[1].Invoked += OnRename;
}
// Set the ItemsSource of the ListView in the XAML to the ObservableCollection.
ListListView.ItemsSource = ListList;
// Calls OnPropertyChanged() which makes the ListView update.
OnPropertyChanged("ListList");
}
}
...
}
}

Related

How to add a list of UIelement in Windows Phone

I want to create a page with dynamic control in windows phone.
While doing this I also want to show a progress bar
Below is my code
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
progressstackPanel.Visibility = Visibility.Visible;//progress bar
formScreen = this;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (!isfst)
{
DrawScreen();
}
else
{
//xTitlePanel is only stack panel in my xaml with vertical orientation
xTitlePanel.UpdateLayout();
}
isfst = true;
progressstackPanel.Visibility = Visibility.Collapsed;
});
}
//Code of DrawScreen which is adding control to my stack panels
private void DrawScreen()
{
if (frm_getset.ChildList != null)
{
String[] arr = frm_getset.ChildList.Split(',');
xTitlePanel.Children.Clear();
PrepareControls prepcontrol = new PrepareControls();
foreach (AttributeGetSet a in _Attribute)
{
//this will return a stackpanel containing
// button/textbox etc.depending on a
StackPanel sp = prepcontrol.getControl(i, a.Label, a, formScreen);
try
{
xTitlePanel.Children.Add(sp);
///Here I get a eception only one control is added first one
/// for anyone it is getting a exception Argument
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
i += 1;
}
The system is adding only one control and when ever it try to execute xTitlePanel.Children.Add(sp); it will get an exception.
I solved the problem ,"xTitlePanel" is a StackPanel I created in my XAML. I found you can not add more that one element from Dispatcher to a control crated on xaml. Like that. so I have to create local stack and add controls to the that local stack panel then and after complete I add the local stack panel to xTitlePanel. NOW my code looks like below
filteredList = new List<FormGetSet>();
if (frm_getset.ChildList != null)
{
String[] arr = frm_getset.ChildList.Split(',');
foreach (String x in arr)
{
filteredList.Add(_template.list_fromgetset.Where(p => p.FormID.Contains(x.Trim())).ToList()[0]);
}
}
xTbox_FormNameHeader.Text = frm_getset.NAME;
_Attribute = new List<AttributeGetSet>();
_Attribute = frm_getset.list_attributegetset;
xTitlePanel.Children.Clear();
StackPanel spPanel = new StackPanel();
spPanel.Orientation = System.Windows.Controls.Orientation.Vertical;
spPanel.Background = new SolidColorBrush(Colors.Transparent);
//xTitlePanel.Children.Add(PrepareControls.getControl(1, "LABEL", "16"));
int i = 1;
// List<AttributeGetSet> _Attribute2 = new List<AttributeGetSet>();
foreach (AttributeGetSet a in _Attribute)
{
PrepareControls prepcontrol = new PrepareControls();
StackPanel sp= prepcontrol.getControl(i, a.Label, a, this);
try
{
spPanel.Children.Add(sp);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
//xTitlePanel.Background = new SolidColorBrush(Colors.White);
//_Attribute2.Add(a);
i += 1;
}
xTitlePanel.Children.Add(spPanel);

Windows 8 Emulator Snap State

How do I enter snap state using the Windows 8 emulator? I received a notice from the Windows 8 store that my software crashes in snap mode only. Does anyone know why switching modes would cause my software to crash? Here is my code behind:
namespace MenuFinderWin8.Pages
{
public sealed partial class RestaurantHomePage : MenuFinderWin8.Common.LayoutAwarePage
{
MenuFinderAppServiceClient serviceClient;
RestaurantRepository repository;
Geolocator _geolocator = null;
ObservableCollection<RestaurantLocation> items;
public RestaurantHomePage()
{
this.InitializeComponent();
if (!Network.IsNetwork())
{
return;
}
repository = new RestaurantRepository();
serviceClient = new MenuFinderAppServiceClient();
_geolocator = new Geolocator();
items = new ObservableCollection<RestaurantLocation>();
BindData();
}
void btnAbout_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
SupportUserControl userControl = new SupportUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 200;
f.Height = 200;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnSearch_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
RestaurantSearchUserControl userControl = new RestaurantSearchUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 600;
f.Height = 400;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnViewFavorites_Click(object sender, RoutedEventArgs e)
{
App.DataMode = Mode.SavedRestaurant;
if (repository.GetGroupedRestaurantsFromDatabase().Count() == 0)
{
MessageDialog messageDialog = new MessageDialog("You have no saved restaurants.", "No Restaurants");
messageDialog.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(RestaurantSearchDetails));
}
}
private async void BindData()
{
try
{
items = await serviceClient.GetSpecialRestaurantsAsync();
List<RestaurantLocation> myFavs = repository.GetRestaurantLocations();
foreach (var a in myFavs)
{
items.Add(a);
}
this.DefaultViewModel["Items"] = items;
}
catch (Exception)
{
MessageDialog messsageDialog = new MessageDialog("The MenuFinder service is unavailable at this time or you have lost your internet connection. If your internet is OK, please check back later.", "Unavailable");
messsageDialog.ShowAsync();
btnAbout.IsEnabled = false;
btnSearch.IsEnabled = false;
btnViewFavorites.IsEnabled = false;
}
myBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
}
private void itemGridView_ItemClick_1(object sender, ItemClickEventArgs e)
{
App.CurrentRestaurantLocation = e.ClickedItem as RestaurantLocation;
if (App.CurrentRestaurantLocation != null)
{
Order order = repository.AddOrder(DateTime.Now, string.Empty, App.CurrentRestaurantLocation.ID);
App.CurrentOrder = order;
App.DataMode = Mode.Menu;
this.Frame.Navigate(typeof(RootViewPage));
}
}
}
}
In response to "How do I enter snap state using the Windows 8 emulator?" - I find the easiest way to snap in the simulator is to use the keyboard shortcut, which is Windows key + . (period).
The error might be in your XAML, more than in the code behind. If you used a template but deleted or modified the name in one of the elements, the KeyFrame refering to that element is failing getting the element, so an exception is thrown.
Search in your XAML for something like
<VisualState x:Name="Snapped">
<Storyboard>...
And delete the ObjectAnimationUsingKeyFrames tags which Storyboard.TargetName property is equal to a non-existant element.
Refering on how to enter Snapped Mode on the emulator, is the same as in PC, just grab the App from the top and slide it to a side while holding the click.

SharePoint issue with Eventhandler

PROBLEM: I have a list and if I create a new Item I would like to do the following:
Create a new AutoIncrement Number in Column [AutoGeneratedID]
Use [Titel] and [AutoGeneratedID] to create a HyperLink in the List and a new subsite
The problem is i cant get the [AutogeneratedID] filled with a value because it is an itemadded event but if i try to put the code together in an ItemAdding event, i get a problem as described in the following link:
http://www.sharepoint-tips.com/2006/09/synchronous-add-list-event-itemadding.html
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Diagnostics;
namespace KuC_Solution.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
// -----------------------------------------------------------
try
{
this.EventFiringEnabled = false;
// Column name AutoGeneratedID
string columnName = "AutoGeneratedID";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = properties.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get the current list
SPList list = web.Lists[properties.ListId];
int highestValue = 0;
foreach (SPListItem item in list.Items)
{
if (item[columnName] != null && item[columnName].ToString().Trim() != "")
{
string value = item[columnName].ToString();
try
{
int currValue = int.Parse(value);
if (currValue > highestValue)
highestValue = currValue;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
}
SPListItem currItem = list.Items.GetItemById(properties.ListItem.ID);
currItem[columnName] = (highestValue + 1).ToString();
currItem.SystemUpdate(false);
web.AllowUnsafeUpdates = false;
}
});
this.EventFiringEnabled = true;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
// -----------------------------------------------------------
}
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
//-------------------------------------------------------------
// Get the web where the event was raised
SPWeb spCurrentSite = properties.OpenWeb();
//Get the name of the list where the event was raised
String curListName = properties.ListTitle;
//If the list is our list named SubSites the create a new subsite directly below the current site
if (curListName == "TESTautoNumber")
{
//Get the SPListItem object that raised the event
SPListItem curItem = properties.ListItem;
//Get the Title field from this item. This will be the name of our new subsite
String curItemSiteName2 = properties.AfterProperties["Title"].ToString();
//String curItemSiteName3 = properties.AfterProperties["ID"].ToString();
String mia = properties.AfterProperties["AutoGeneratedID"].ToString();
String curItemSiteName = curItemSiteName2 + mia;
//Get the Description field from this item. This will be the description for our new subsite
//String curItemDescription = properties.AfterProperties["Projekt-ID"].ToString();
string curItemDescription = "CREWPOINT";
//String testme = "1";
//Update the SiteUrl field of the item, this is the URL of our new subsite
properties.AfterProperties["tLINK"] = spCurrentSite.Url + "/" + curItemSiteName;
//Create the subsite based on the template from the Solution Gallery
SPWeb newSite = spCurrentSite.Webs.Add(curItemSiteName, curItemSiteName, curItemDescription, Convert.ToUInt16(1033), "{4ADAD620-701D-401E-8DBA-B4772818E270}#myTemplate2012", false, false);
//Set the new subsite to inherit it's top navigation from the parent site, Usefalse if you do not want this.
newSite.Navigation.UseShared = true;
newSite.Close();
}
//---------------------------------------------------------------
}
}
}

DataBinding Snapped Mode Windows 8

Using a GridView, I bind to several items in an observable collection. When I enter snapped mode, my GridView fails to load any data and none of the items are clickable. See attached screenshot. My app is on the left and it says featured and favorites. Here is my code:
public sealed partial class RestaurantHomePage : MenuFinderWin8.Common.LayoutAwarePage
{
MenuFinderAppServiceClient serviceClient;
RestaurantRepository repository;
Geolocator _geolocator = null;
ObservableCollection<RestaurantLocation> items;
public RestaurantHomePage()
{
this.InitializeComponent();
if (!Network.IsNetwork())
{
return;
}
repository = new RestaurantRepository();
serviceClient = new MenuFinderAppServiceClient();
_geolocator = new Geolocator();
items = new ObservableCollection<RestaurantLocation>();
//BindData();
}
void btnAbout_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
SupportUserControl userControl = new SupportUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 200;
f.Height = 200;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnSearch_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
RestaurantSearchUserControl userControl = new RestaurantSearchUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 600;
f.Height = 400;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnViewFavorites_Click(object sender, RoutedEventArgs e)
{
App.DataMode = Mode.SavedRestaurant;
if (repository.GetGroupedRestaurantsFromDatabase().Count() == 0)
{
MessageDialog messageDialog = new MessageDialog("You have no saved restaurants.", "No Restaurants");
messageDialog.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(RestaurantSearchDetails));
}
}
private async void BindData()
{
try
{
items = await serviceClient.GetSpecialRestaurantsAsync();
List<RestaurantLocation> myFavs = repository.GetRestaurantLocations();
foreach (var a in myFavs)
{
items.Add(a);
}
this.DefaultViewModel["Items"] = items;
}
catch (Exception)
{
MessageDialog messsageDialog = new MessageDialog("The MenuFinder service is unavailable at this time or you have lost your internet connection. If your internet is OK, please check back later.", "Unavailable");
messsageDialog.ShowAsync();
btnAbout.IsEnabled = false;
btnSearch.IsEnabled = false;
btnViewFavorites.IsEnabled = false;
}
myBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
BindData();
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
}
private void itemGridView_ItemClick_1(object sender, ItemClickEventArgs e)
{
App.CurrentRestaurantLocation = e.ClickedItem as RestaurantLocation;
if (App.CurrentRestaurantLocation != null)
{
Order order = repository.AddOrder(DateTime.Now, string.Empty, App.CurrentRestaurantLocation.ID);
App.CurrentOrder = order;
App.DataMode = Mode.Menu;
this.Frame.Navigate(typeof(RootViewPage));
}
}
}
When you switch to snapped view, your gridView hides, and a ListView shows up. You can see this by checking the Visual State Manager that handles going from one to another in your XAML.
So, Solution is: adapting the ItemTemplate from your ListView as you did with your GridView by Binding to the proper attributes; you may also want to change the Foreground color of your Font. Also, you want to include the IsItemClickEnabled and ItemClick (or SelectionMode and SelectionChanged) on your ListView.

Set the value of custom webpart property in c#

How to set the value of custom webpart property Programatically in C#.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite SiteCollection = new SPSite(mySiteGuid))
{
SPWeb myWeb = SiteCollection.OpenWeb(myWebGuid);
myWeb .AllowUnsafeUpdates = true;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = myWeb.GetLimitedWebPartManager ("default.aspx",System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
{
if (myWebPart.Title == "Other Webpart Name")
{
myWebPart.Visible = ! myWebPart.Visible;
myWeb.Update();
break;
}
}
}
});
I have a custom property in the webpart of type string to get the input from the user.
I wanted to updated the value of the property from c#.
Is there any way to set the value?
TIA
Try myWebPart.Update() instead of myWeb.Update().
Maybe it's a bit late for the answer, but here i let a piece of code i used for this.
var webCollection = new SPSite("http://mySharePointSite").AllWebs;
foreach (SPWeb web in webCollection)
{
var landingPageReference = #"/Pages/default.aspx";
var page = web.GetFile(landingPageReference);
if (!page.Exists)
continue;
page.CheckOut();
var spLimitedWebPartManager = web.GetLimitedWebPartManager(page.ServerRelativeUrl, PersonalizationScope.Shared);
foreach (WebPart webPartItem in spLimitedWebPartManager.WebParts)
{
if (webPartItem.Title.Equals("myWebPartTitle"))
{
// Specify Properties to change here
webPartItem.ChromeType = PartChromeType.Default;
webPartItem.Description = "AGAIN CHANGED";
// Save made changes
spLimitedWebPartManager.SaveChanges(webPartItem);
break;
}
}
page.CheckIn("Add Comment if desired");
page.Publish("Add Comment if desired");
web.Update();
web.Dispose();
}