【问题标题】:binding an editable combobox and detect inserted text in wpf绑定可编辑的组合框并检测 wpf 中插入的文本
【发布时间】:2012-05-16 06:36:59
【问题描述】:

我有一个ComboBox,它看起来像这样:

<ComboBox
    ItemsSource="{Binding JobList}"
    SelectedValue="{Binding Job,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
    DisplayMemberPath="Title"
    SelectedValuePath="Id"
    IsEditable="True"
    StaysOpenOnEdit="True"
    />

它与我的ViewModel 的绑定看起来像这样:

public class ViewModel {
    // this will fill from a database record for a person
    public Job Job {
        get { return _job; }
        set {
            if(value == _job) return;
            _job = value;
            OnPropertyChanged( () => Job );
        }
    }
    // this will fill from all jobs records in database
    public ObservableCollection<Job> JobList 
    { /* do same as Job to implementing INotifyPropertyChanged */ }
}

Job 是:

public class Job {
    public int Id { get; set; }
    public string Title { get; set; }
}

真的,我想用工作列表填写ComboBox。所以如果用户指定的Job在列表中,用户可以从列表中选择它,否则,他在ComboBox中输入一个新的Job.Title,视图模型通知它,并创建一个新的Job项目并且还将其添加到JobList

你有什么想法吗?你能帮帮我吗?

【问题讨论】:

  • 那么到底是什么不起作用?从您发布的内容来看,一切似乎都是正确的。另外,您能否发布您如何设置视图的 DataContext?
  • 看@Simon_D 建议here
  • 问题是Job 属性的类型是Job 并且组合框文本输入无法被viewmodel 检测到。如果我设置string 类型的Job 并绑定ComboBox.Text 属性,那么我无法检测到所选项目的Id

标签: c# wpf mvvm combobox wcf-binding


【解决方案1】:
  1. 在 viewModel 中创建一个类似于“SelectedJobName”的字符串属性
  2. 将此属性绑定到 Combobox.Text
  3. 无论您想在何处使用输入的值(Command、Presenter),请检查所选值是否不为空且 selectedJobName 属性值是否不匹配。

【讨论】:

  • 迟到但很好 :D 我以前也这样做过。但你是新来的,所以我接受并投票赞成你的答案。欢呼
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多