'How to go to a new page with selectedItem in Picker In Xamarin
I have a Picker in Xamarin and I want to go to the page which is selected in Picker. So here is my view in Picker:
<ContentPage.Content>
<ScrollView>
<StackLayout Margin="20">
<Label Text="List of tables" FontAttributes="Bold" HorizontalOptions="Center"/>
<Picker Title="Select table" ItemsSource="{Binding TablesFromViewModelCollector}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedTable}" />
<Label Text="{Binding SelectedTable.Name}" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}"/>
<Button Text="Select Table" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}" Clicked="Selected_Button"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
Here is it's contoller:
public TablePage()
{
InitializeComponent();
BindingContext = new TableViewModel();
}
async void Selected_Button(object sender, System.EventArgs e)
{
await Navigation.PushAsync(new TableDetails());
}
And here is TableViewModel where I can select the table from Picker:
class TableViewModel : INotifyPropertyChanged
{
public IList<Table> TablesFromViewModelCollector { get { return TableData.Tables; } }
Table selectedTable;
public Table SelectedTable
{
get { return selectedTable; }
set
{
if(SelectedTable != value)
{
selectedTable = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
So I added button under the Picker as you see. And what I am trying to achieve, when the Picker is selected and button is clicked, goes to the page of TableDetails. In this page, I want to show the data of selectedTable. Basically, here is my view for TableDetails:
<ContentPage.Content>
<ScrollView>
<StackLayout Margin="20">
<Label Text="{Binding SelectedTable.Name}" HorizontalOptions="Center" Style="{DynamicResource TitleStyle}"/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
And here is my controller:
public partial class TableDetails : ContentPage
{
public TableDetails()
{
InitializeComponent();
BindingContext = new TableViewModel();
}
}
But I dont get the value of the selectedTable.
Solution 1:[1]
just pass the value on the constructor
await Navigation.PushAsync(new TableDetails(VM.SelectedTable));
then modify the page constructor
public TableDetails(Table selected)
{
InitializeComponent();
BindingContext = new TableViewModel();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jason |
