Search code examples
c#listwindows-phone-8datasourcelonglistselector

get longListSelector source from a different view


I'm following this example: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj244365%28v=vs.105%29.aspx

When the application launches for the first time I want to add certain items to a list, these will not be able to be removed. So in the App.xaml.cs I have:

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
    List<MyConnection.locationList.locations> source = new List<MyConnection.locationList.locations>();

    if (!settings.Contains("firstrun"))
    {
        source.Add(new MyConnection.locationList.locations("Dulles, VA"));
        source.Add(new MyConnection.locationList.locations("Dulles, VA (Q)"));
    }
}

In my locationList.xaml.cs (which is where the longListSelector will be) I have:

public locationList()
{
    InitializeComponent();

    List<locationSelectorClass.locationChoice<locations>> DataSource = locationSelectorClass.locationChoice<locations>.CreateGroups(source,
        System.Threading.Thread.CurrentThread.CurrentUICulture,
        (locations s) => { return s.LastName; }, true);
}

public class locations
{
    public string locName
    {
        get;
        set;
    }

    public locations(string locName)
    {
        this.locName = locName;
    }
}

Obviously it's stating that it can't find 'source', so how can I instruct it to look in the App.xaml.cs or how to I call source once it's been created?

I have tried "MyConnection.App.xxxx" but it doesn't give me an option for "source".


Solution

  • If you want to use Myconnection.App.xxxx

    You have to make source public, and if you want to get the information you have to write

    List<MyConnection.locationList.locations> source;
    private void Application_Launching(object sender, LaunchingEventArgs e)
        {
    
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            source = new List<MyConnection.locationList.locations>();
    
            if (!settings.Contains("firstrun"))
            {
                source.Add(new MyConnection.locationList.locations("Dulles, VA"));
                source.Add(new MyConnection.locationList.locations("Dulles, VA (Q)"));
            }
    }
    

    Now you are able to get the information. However using statics are not allways the best way. Which mean you could make the search in settings in the locationlist() constructor. Or you could parse some information with navigation. But maybe for the first sample the method you suggested see code, or loading the info in the constructor would be best.

    Extra

    If you want to add/remove entries to the list, and show them in the GUI, you should use ObservableCollection instead of List.