要求
我想要一个ComboBox
,用户可以输入一些文本或从下拉列表中选择文本。当用户在键入后按Enter或仅从下拉列表中选择项目时,绑定源应更新(在我的情况下最佳的显示行为)。
问题
- 当设置
UpdateSourceTrigger=PropertyChange
(默认值)时,每输入一个字符便会触发源更新,这不好,因为调用属性设置器是昂贵的; - 当设置
UpdateSourceTrigger=LostFocus
时,选择下拉列表中的项将需要更多操作才能实际失去焦点,这对用户不太友好(需要点击两次才能选择项)。
我尝试使用UpdateSourceTrigger=Explicit
,但结果不尽如人意:
<ComboBox IsEditable="True" VerticalAlignment="Top" ItemsSource="{Binding List}"
Text="{Binding Text, UpdateSourceTrigger=LostFocus}"
SelectionChanged="ComboBox_SelectionChanged"
PreviewKeyDown="ComboBox_PreviewKeyDown" LostFocus="ComboBox_LostFocus"/>
public partial class MainWindow : Window
{
private string _text = "Test";
public string Text
{
get { return _text; }
set
{
if (_text != value)
{
_text = value;
MessageBox.Show(value);
}
}
}
public string[] List
{
get { return new[] { "Test", "AnotherTest" }; }
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
}
private void ComboBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
}
private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
{
((ComboBox)sender).GetBindingExpression(ComboBox.TextProperty).UpdateSource();
}
}
这段代码存在两个问题:
- 当从下拉菜单中选择项目时,源会更新为以前选择的值,为什么?
- 当用户开始输入内容,然后点击下拉按钮从列表中选择内容时,源再次更新(由于失去焦点?),如何避免这种情况?
Delay
很好。如果它按照我理解的方式工作,这看起来是一个非常好的解决方法。 - Sinatr