我有一个带有列表框的wpf应用程序。我尝试访问listbox.selectedValue但它是null,我不明白。它甚至有一个默认选择,为什么它一直保持为空?非常感谢任何线索
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");
}
和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"/>
答案 0 :(得分:1)
试试这段代码:
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");