2017-05-20 4 views
1

私はリストボックスを持つwpfアプリケーションを持っています。私はlistbox.selectedValueにアクセスしようとしますが、それはnullです。理解できません。それはデフォルト選択を持っているので、なぜそれがnullのままになるのでしょうか?任意の手掛かりが大幅C#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"/> 
+3

あなたは 'SelectedValue'プロパティの目的について混乱しています。混乱を解消するには、[この回答を読む](http://stackoverflow.com/a/4902454/2819245)を参照してください。一方、あなたが使用したいのは、リストボックスの 'SelectedItem'プロパティか、' SelectedValuePath'と一緒に 'SelectedValue'です。また、XAMLのListBoxItem.Selectedイベントで何をしますか?それは本当に良く見えません。おそらく、データバインディングとMVVMを使用して適切なWFPを実行する方法を調べる必要があります。 – elgonzo

+0

ありがとうございます。SelectedItemで同じエラーが発生しました。私はSelectedValuePathを完全に理解していませんが、 –

答えて

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"); 
関連する問題