2

I have a wpf application with a listbox. I try to access the listbox.selectedValue but it is null, which I dont understand. It even has a default selection so why does it keep being null? ANy clues are greatly appreciated

private void save_Click_1(object sender, RoutedEventArgs e)
{
    string name = foodName.Text;
    string type = preferenceType.SelectedValue.ToString();
    Preference newPreference = new Preference(name, type);
    string temp = name + ";" + type;
    newPreference.save(temp, newPreference.path);
    MessageBox.Show($"{name} {type} saved");
}

And the xaml:

<TextBox x:Name="foodName" TextWrapping="Wrap" Text="Food name" GotFocus="foodName_GotFocus" HorizontalScrollBarVisibility="Auto" Grid.ColumnSpan="3" Margin="1.4,50,10.2,280" Grid.Column="1"/>
<ListBox x:Name="preferenceType" Grid.ColumnSpan="3" Margin="1.4,81,10.2,246" Grid.Column="1">
    <ListBoxItem Selected="ListBoxItem_Selected">allergy</ListBoxItem>
    <ListBoxItem Selected="ListBoxItem_Selected">hate</ListBoxItem>
    <ListBoxItem Selected="ListBoxItem_Selected">dislike</ListBoxItem>
</ListBox>
<Button x:Name="savePreference" Content="Save" HorizontalAlignment="Left" Margin="1.4,115,0,0" VerticalAlignment="Top" Width="78" Click="save_Click_1" Grid.ColumnSpan="3" Grid.Column="1" Height="19"/>
Vitali
  • 645
  • 9
  • 14
Maja Okholm
  • 3,147
  • 2
  • 11
  • 17
  • 3
    You are confused about the purpose of the `SelectedValue` property. Read [this answer](http://stackoverflow.com/a/4902454/2819245) to clear up your confusion. Meanwhile, what you want to use is either the `SelectedItem` property of your listbox, or `SelectedValue` in conjunction with `SelectedValuePath` i guess. Also, what shenanigans do you do with the ListBoxItem.Selected event in your XAML? That doesn't look really good. Perhaps you should look into how to do proper WFP using data binding and MVVM... –  May 20 '17 at 15:33
  • Thanks however I get excatly the same error with SelectedItem - I dont fully understand the SelectedValuePath but I will try to read more about it – Maja Okholm May 20 '17 at 16:12

1 Answers1

1

try this code:

        ListBoxItem testitem = preferenceType.SelectedValue as ListBoxItem;
        string name = foodName.Text;
        string type = testitem.Content.ToString();
        Preference newPreference = new Preference(name, type);
        string temp = name + ";" + type;
        newPreference.save(temp, newPreference.path);
        MessageBox.Show(name + type + "saved");
Dark Templar
  • 1,130
  • 8
  • 10