簡體   English   中英

如何獲取 ComboBox 的值?

[英]How to get the value of a ComboBox?

我有一個 WPF ComboBox,我想從中獲取值。

<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>

我試過這個(如此處所見) 獲得它:

Bets.Add(new Bet() { Name = nameInput.Text, Amount = amount, Choice = (ChoicesList.SelectedValue as ComboBoxItem).Content.ToString() });

但每次我嘗試得到一個System.NullReferenceException: 'Object reference not set to an instance of an object.' 錯誤。 該列表顯然不是空的。

所以我嘗試了另一種方法來獲取它。

Bets.Add(new Bet() { Name = nameInput.Text, Amount = amount, Choice = ChoicesList.SelectedValue.ToString() });

我沒有得到異常,但我也沒有得到我想要的數據。 相反,我得到了PoolBet.MainWindow+Choice

列表初始化:

public ObservableCollection<Choice> Choices { get; set; } = new ObservableCollection<Choice>();

public class Choice
{
    public string ChoiceName { get; set; }
}

我在這里做錯了什么?

看法:

<ComboBox ItemsSource="{Binding Choices}" SelectedItem="{Binding SelectedChoice}"/>

查看model:

public ObservableCollection<Choice> Choices { get; }

private Choice _selectedChoice;
public Choice SelectedChoice 
{
 get
 {
    return _selectedChoice;
 } 
 set
 {
    _selectedChoise = value;
    OnPropertyChanged();
 } 
}

不要忘記為您的視圖 model 實現INotifyPropertyChanged接口,並將視圖 model 設置為視圖的DataContext

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM