简体   繁体   中英

How to get the value of a ComboBox?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM