[英]Wpf editable ComboBox: How do I enter new text to combobox which is not in list by pressing Enter
[英]How to add new values to ComboBox after pressing the ENTER key?
如果您能幫助我,我會很高興。 我是WPF的新手。
我遇到了有關ComboBox的問題。 我正在使用Ado.Net Entity Framework 5從MySql服務器中檢索作業數據。我的ComboBox需要顯示這些作業的ID,並且需要進行編輯才能添加新的ID。 問題是一旦我輸入了組合框中不存在的新ID並按Enter,就什么也沒有發生。 我需要在按ENTER鍵之后將新值添加到ComboBox的綁定列表中。 有人告訴我使用LOSTFOCUS(因為PropertyChange將為每個擊鍵調用,並且每個擊鍵將被視為組合框列表中的新值),但是什么也沒有發生。 還告訴我,它與“行為和命令”有關。 由於我是新手,因此遇到了困難。 您能給我看看這個問題的解決方案示例嗎? :)
public class Job {
public string JobId { get; set; }
public string JobTitle { get; set; }
}
<ComboBox Name="JobIdComboBox" DisplayMemberPath="JobID" ItemsSource="{Binding JobsList, Mode=TwoWay}" SelectedItem ="{Binding JobSelectedItem}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="147" Margin="360,37,0,0" Grid.Row="1" Height="30" FontSize="18" IsReadOnly="False" IsEditable="True" Text="{Binding Path=JobNewItem,UpdateSourceTrigger=LostFocus}"/>
namespace JobsApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
}
public class MainViewModel:INotifyPropertyChanged
{
JobsDbEntities jobsDbEntitiesInstance = new JobsDbEntities();
public MainViewModel()
{
FillJobs();
}
private void FillJobs()
{
var q = (from Jobs in jobsDbEntitiesInstance.certificateheader
select Jobs).ToList();
JobsList = q;
}
private List<Job> _jobsList;
public List<Job> JobsList
{
get { return _jobsList; }
set
{
_jobsList = value;
OnPropertyChanged();
}
}
private Job _jobSelectedItem;
public Job JobSelectedItem
{
get { return _jobSelectedItem; }
set
{
_jobSelectedItem = value;
OnPropertyChanged();
}
}
private string _jobNewItem;
public string JobNewItem
{
get { return _jobNewItem; }
set
{
if (value != null)
{
_jobNewItem = value;
OnPropertyChanged();
var jobNewElement = new Job {JobID = _jobNewItem};
_jobsList.Add(jobNewElement);
JobSelectedItem = jobNewElement;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
你快到了 將UpdateSourceTrigger從LostFocus更改為PropertyChanged。
Text="{Binding Path=JobNewItem,UpdateSourceTrigger=PropertyChanged}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.