Reputation: 72
I have a WPF ComboBox that I want to get the value from.
<ComboBox Name="ChoicesList" Grid.Column="2" Grid.Row="2" Margin="0,0,10,10">
<ComboBox.ItemTemplate>
<DataTemplate>
<ComboBoxItem Content="{Binding ChoiceName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
I tried this (as seen here) to get it:
Bets.Add(new Bet() { Name = nameInput.Text, Amount = amount, Choice = (ChoicesList.SelectedValue as ComboBoxItem).Content.ToString() });
But every time I try to I get a System.NullReferenceException: 'Object reference not set to an instance of an object.'
error. The list is clearly not empty.
So I tried another way to get it.
Bets.Add(new Bet() { Name = nameInput.Text, Amount = amount, Choice = ChoicesList.SelectedValue.ToString() });
I don't get an exception but I also did not get the data I want. I instead got PoolBet.MainWindow+Choice
.
List initialization:
public ObservableCollection<Choice> Choices { get; set; } = new ObservableCollection<Choice>();
public class Choice
{
public string ChoiceName { get; set; }
}
What am I doing wrong here?
Upvotes: 0
Views: 104
Reputation: 44
View:
<ComboBox ItemsSource="{Binding Choices}" SelectedItem="{Binding SelectedChoice}"/>
View model:
public ObservableCollection<Choice> Choices { get; }
private Choice _selectedChoice;
public Choice SelectedChoice
{
get
{
return _selectedChoice;
}
set
{
_selectedChoise = value;
OnPropertyChanged();
}
}
Do not forget to implement INotifyPropertyChanged
interface for your view model and to set view model as DataContext
for view.
Upvotes: 1