Question

I have a listPicker in a windows phone 8 app, and wondering what I'm doing wrong to collect the currently selected item in c#.

Here's the XAML for the listPicker.

<toolkit:ListPicker x:Name="brewMethodList" HorizontalAlignment="Left" Margin="-2,24,0,0" VerticalAlignment="Top" Height="127" Width="164" BorderBrush="#FF162E3E" Foreground="Black" SelectionChanged="brewMethodSelectionChange" LostFocus="quantityInputLostFocus" Background="#FF5C97BF" >
  <toolkit:ListPickerItem x:Name="manual_list" Content="Manual" Background="#FF5C97BF"/>
  <toolkit:ListPickerItem x:Name="autoDrip_list" Content="Auto Drip" Background="#FF5C97BF"/>
</toolkit:ListPicker>

Here's the c# trying to access the currently selected Item.

private void brewMethodSelectionChange(object sender, SelectionChangedEventArgs e)
    {
        if (brewMethodList.SelectedItem == manual_list)
        {
            brewMethod = MANUAL;
        }
        else
        {
            brewMethod = AUTO_DRIP;
        }
        update();
    }

This is just a simplified version, but it throws a 'System.NullReferenceException' and if I hover my mouse over "brewMethodList" it says null, and the same goes for hovering my mouse over "manual_list."

On behalf of being new, I'm not entirely knowledgeable on databinding, and if that is what I should be doing just let me know, but I thought I could manage without it (plus I'm not solid on what its capable of). Anything is much appreciated! I've read just about every article I could find.

Was it helpful?

Solution

Try this

    private void brewMethodSelectionChange(object sender, SelectionChangedEventArgs e)
    {
        var brewMethodList = sender as ListPicker;
        if (brewMethodList.SelectedItem == manual_list)
        {
            brewMethod = MANUAL;
        }
        else
        {
            brewMethod = AUTO_DRIP;
        }
        update();
    }

But yes, it is more better if you use the MVVM pattern. This link should be a good reference, http://msdn.microsoft.com/en-us/magazine/hh852595.aspx

EDIT: It is also better if you don't check through the name of the controls, once you implement MVVM pattern it will be a lot cleaner and simpler to do rather than doing everything behind the code. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top