如果你能帮助我,我会很高兴的。我是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));
}
}
答案 0 :(得分:0)
你快到了。将UpdateSourceTrigger从LostFocus更改为PropertyChanged。
Text="{Binding Path=JobNewItem,UpdateSourceTrigger=PropertyChanged}"/>