Closed ebuildr closed 1 year ago
Without being able to see what you've tried, I'd just be guessing at what's gone wrong. (Hint. If you can show what you've tried--not just provide a description of it, it makes it easier to help.)
Here's a quick example of how you could do this.
I started by creating a new app:
ListDetail
page (in addition to the default blank page.)I then made the following changes.
I changed MainViewModel.cs
to be like this:
public partial class MainViewModel : BaseViewModel
{
readonly SampleDataService dataService;
[ObservableProperty]
ObservableCollection<string> items;
public MainViewModel(SampleDataService service)
{
dataService = service;
}
public async Task LoadItems()
{
var allItems = await dataService.GetItems();
// Note only taking 10 items - but that's totally optional
Items = new ObservableCollection<string>(allItems.Take(10).Select(i => i.Title).ToList());
}
}
In MainPage.xaml
I added the following:
<Picker ItemsSource="{Binding Items}" />
And finally, I changed MainPage.xaml.cs
to add the OnNavigatedTo
method:
public partial class MainPage : ContentPage
{
public MainPage(MainViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
protected override async void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
await (BindingContext as MainViewModel).LoadItems();
}
}
When running the app, when the MainPage loads the data when navigated to. This is then available from the picker.
Screenshots (from Windows)
When the page loads:
Click on it and see the options available.
And with the selected option shown:
The SampleDataService
is a simple abstraction over a way to get some data. Obviously, you'd get real data from another source. If you know the options you want in the picker at design-time, you will load them differently, too. ;)
Thanks for the detailed answer I was trying to add a picker to the ListDetailDetailPage. The picker would show up but would not load data. I am still not sure why, maybe it is just not the correct approach to repurpose that page. I then moved on to using the Main page as you did in the example.
I'll assume you've worked out a suitable solution then.
Describe the bug I'm sure it's just me, but I can not seem to add a picker bound to the service that is generated. I am using the ListDetail and I am trying to add or replace the Labels with a picker. Perhaps this service was not intended to do this and this should be a feature request. The error is ' cannot be converted to type 'System.Collections.IList'. I have used all three coding styles. Thanks, I have found the accelerator very helpful.