Search code examples
c#uwpvisual-studio-2017

C# UWP VS2017 ComboBox event error: unable to activate Windows store app


I tried to create an eventhandler for a combobox in an UWP app that when I change the value to a certain item some controls on the form get hidden. The problem is that when I choose to start without debugging I get an error: unable to activate Windows store app. Now I dont know is this is caused by the code or by something else. When I remove the event from the code the problem is gone and if I only remove the body from the eventhandler the problem remains so I am fairly certain the problem is not in the body.

This is the C# + XAML code:

private void RoleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (roleComboBox.SelectionBoxItem.ToString() == "Coach")
        {
            positionTextBlock.Visibility = Visibility.Collapsed;
            positionComboBox.Visibility = Visibility.Collapsed;
        }
    }

<ComboBox x:Name="roleComboBox" HorizontalAlignment="Left" Margin="200,84,0,0" VerticalAlignment="Top" Width="140" SelectionChanged="RoleComboBox_SelectionChanged">
        <ComboBoxItem IsSelected="True">-Choose a role-</ComboBoxItem>
        <ComboBoxItem>Player</ComboBoxItem>
        <ComboBoxItem>Coach</ComboBoxItem>
        <ComboBoxItem>Trainer</ComboBoxItem>
    </ComboBox>

I first thought the problem was somewhere in VS2017 (also tried 2019) and tried a lot of solutions I found on the internet regarding this problem. After trying solutions for 10+ hours (I never thought the problem was in the code as all the problems on the internet descriped it as a problem with the debugger) I tried to comment the last part I coded as the problem occured at that time and wasnt there before that. This solved my problem so I pinpointed the error to the eventhandler.


Solution

  • The problem is that you place ComboBoxItem in the ComboBox, so the selected item type is ComboBoxItem, we need to convert it to ComboBoxItem then get Content property like the following.

    private void RoleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var item = roleComboBox.SelectedItem as ComboBoxItem;
        var value = item.Content;
        if ((roleComboBox.SelectedItem as ComboBoxItem).Content.ToString() == "Coach")
        {
            positionTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
          
        }
    }