panthor314
panthor314

Reputation: 318

How to retrieve objects property info from data binding

I have a Xamarin Forms application where I populate a list view with a list of objects of type Student. I want to be able to select this student and open an alert that displays the name of the student selected. My current attempt only displays the type of the object (Student) in the alert. Here is my approach:

AttendancePage.xaml:

<ListView x:Name="RosterInView" SeparatorVisibility="None" ItemSelected="OnSelection">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding complete_name}"
            Detail="{Binding grade}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And in my AttendancePage.xaml.cs I'm having difficulty getting the binding property down:

protected override void OnAppearing()
    {
        base.OnAppearing();
        IEnumerable<Student> roster = _database.GetItems();

        RosterInView.ItemsSource = roster;

    }
void OnSelection(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem == null)
            return;
        // real trouble starts here with how to refer to "complete_name" as seen in the xaml file
        DisplayAlert("Item Selected", ((ListView)sender).SelectedItem.ToString(), "OK");
    }

Upvotes: 2

Views: 215

Answers (1)

panthor314
panthor314

Reputation: 318

Pretty simple solution thanks to @RoyiMindel for pointing it out, instead of

 DisplayAlert("Item Selected", ((ListView)sender).SelectedItem.ToString(), "OK");

it should be:

DisplayAlert("Item Selected", (((ListView)sender).SelectedItem as Student).complete_name, "OK");

Upvotes: 3

Related Questions