Pxaml
Pxaml

Reputation: 553

access properties of the selectedItem xamarin forms

Trying to access the property{Name} inside a list , using slectedItem ex.

 var SName = e.SelectedItem;

            if (e.SelectedItem == null)
            {
                return;
            }
            await DisplayAlert("Item Selected", SName.ToString(), "Ok");

the common way will be just var SName = e.SelectedItem.Name;. However I dont get the option to access it . I already have the get;set; and if I add a breakpoint on the mention line it shows me the Name property and value that I want to display. any suggestion ? Thanks

Upvotes: 0

Views: 431

Answers (2)

Todd Skelton
Todd Skelton

Reputation: 7239

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast

You can use the type-testing operators to make it look cleaner. (C# 7.0+)

if(e.SelectedItem is MyType item)
{
  var name = item.Name;
  await DisplayAlert("Item Selected", name, "Ok");
}
return;

Upvotes: 0

Jason
Jason

Reputation: 89082

e.SelectedItem is of type object - you need to cast it to the appropriate type first

var item = (MyType) e.SelectedItem;
var name = item.Name;

Upvotes: 1

Related Questions