【问题标题】:How to get the value of a ComboBox?如何获取 ComboBox 的值?
【发布时间】:2021-10-24 12:39:54
【问题描述】:

我有一个想要从中获取值的 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>

我试过这个(如 here 所示)来得到它:

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.' 错误。该列表显然不是空的。

所以我尝试another way 得到它。

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

我在这里做错了什么?

【问题讨论】:

  • 在您的第一次尝试中,您尝试将 ChoicesList.SelectedValue 转换为 ComboBoxItem,但如果您将其绑定到 ObservableCollection Choices,则 SelectedValue 的类型是 Choice 而不是 @987654335 @,导致 NullReferenceException。对于第二次尝试,尽管您没有覆盖该方法,但您直接在对象上使用 ToString(),您有两个选择:1. Choice = (ChoicesList.SelectedValue as Choice).ChoiceName 和 2. 在您的类中添加 ToString() 方法 Choice
  • 非常感谢!它现在可以完美运行。如果不是评论,将设置为答案。
  • 不是直接关于您的问题,而是当模板是默认模板时,数据模板化项目的意义何在..?我想你可以设置 DisplayMemberPath="ChoiceName"
  • @SpaceNerden 实际上 Ivan 的回答值得您在 MVVM 中查看,因为您的 SelectedValue 可以始终位于 ViewModel 的属性中

标签: c# wpf combobox


【解决方案1】:

查看:

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

查看模型:

public ObservableCollection<Choice> Choices { get; }

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

不要忘记为您的视图模型实现INotifyPropertyChanged 接口,并将视图模型设置为DataContext 用于视图。

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多