我有一个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 */ }
}
而工作是:
public class Job {
public int Id { get; set; }
public string Title { get; set; }
}
确实,我想用作业列表填充ComboBox.因此,如果用户指定的Job在列表中,则用户可以从列表中选择它,否则,他会在ComboBox中输入新的Job.Title,视图模型会对其进行通知,并创建一个新的Job项目并将其添加到JobList中.
你有什么主意吗你能帮我吗?
解决方法:
>在viewModel中创建一个字符串属性,例如“ SelectedJobName”
>将此属性绑定到Combobox.Text
>无论您要在何处使用输入的值(Command,Presenter),请检查所选值是否不为空,并且selectedJobName属性值是否不匹配.