Bhanuprakash Mankala Bhanuprakash Mankala - 1 year ago 87
C# Question

Pivot SelectedItem property is causing crash in Windows UWP

As shown in the below code i have used a pivot control to display data and in the selection changed of pivot control i have called a method so that it will select the header value dynamically and displays the data.

XAML Code:

<Pivot x:Name="pivot" SelectionChanged="BindData">
<PivotItem Header="Test1"></PivotItem>
<PivotItem Header="Test2"></PivotItem>
</Pivot>


C# Code:

private async void BindData(object sender, SelectionChangedEventArgs e)
{
dynamic selectedValue = pivot.SelectedItem;
if (selectedValue != null)
{
PropertyInfo pi = selectedValue.GetType().GetProperty("Header");
string sectionName = (String)(pi.GetValue(selectedValue, null));
}
}


The code is working seamlessly fine in the Debug mode, but causing a crash in the release mode.
What might be the issue for this? Any workaround? or any settings i am missing?
Kindly help me on this issue.
Thank you.

Answer Source

I don't understand why you're using reflection when you don't need to?

The PivotItem class exposes the Header property, so you can just use:

private void BindData(object sender, SelectionChangedEventArgs e)
{
    var selectedItem = pivot.SelectedItem as PivotItem;    // Gets the selected item and casts it from an object to a PivotItem.
    var sectionName = selectedItem?.Header as string;      // "selectedItem?" - makes sure selectedItem isn't null. ".Header as string" - gets the Header property and casts it from an object to  a string.
}

That should work just fine in Release mode.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download