我想创建具有以下属性的可编辑组合框:
更新以下事件的数据模型:
我已经能够创建这样的控件,但它非常丑陋(使用许多黑客),我希望有一种更简单的方法......
提前致谢
答案 0 :(得分:2)
好的,我这就是我所做的,而不是那么丑:
/// <summary>
/// Editable combo box which updates the data model on the following:
/// 1. Select## Heading ##ion changed
/// 2. Lost focus
/// 3. Enter or Return pressed
///
/// In order for this to work, the EditableComboBox requires the follows, when binding:
/// The data model value should be bounded to the Text property of the ComboBox
/// The binding expression UpdateSourceTrigger property should be set to LostFocus
/// e.g. in XAML:
/// <PmsEditableComboBox Text="{Binding Path=MyValue, UpdateSourceTrigger=LostFocus}"
/// ItemsSource="{Binding Path=MyMenu}"/>
/// </summary>
public class PmsEditableComboBox : ComboBox
{
/// <summary>
/// Initializes a new instance of the <see cref="PmsEditableComboBox"/> class.
/// </summary>
public PmsEditableComboBox()
: base()
{
// When TextSearch enabled we'll get some unwanted behaviour when typing
// (i.e. the content is taken from the DropDown instead from the text)
IsTextSearchEnabled = false;
IsEditable = true;
}
/// <summary>
/// Use KeyUp and not KeyDown because when the DropDown is opened and Enter is pressed
/// We'll get only KeyUp event
/// </summary>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
// Update binding source on Enter
if (e.Key == Key.Return || e.Key == Key.Enter)
{
UpdateDataSource();
}
}
/// <summary>
/// The Text property binding will be updated when selection changes
/// </summary>
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
UpdateDataSource();
}
/// <summary>
/// Updates the data source.
/// </summary>
private void UpdateDataSource()
{
BindingExpression expression = GetBindingExpression(ComboBox.TextProperty);
if (expression != null)
{
expression.UpdateSource();
}
}
}
答案 1 :(得分:0)
执行此操作的最简单方法是在绑定上使用UpdateSourceTrigger属性。您可能无法准确匹配当前行为,但您可能会发现它具有可比性。
UpdateSourceTrigger属性控制绑定目标何时更新源。绑定时,不同的WPF控件对此属性具有不同的默认值。
以下是您的选择:
UpdateSourceTrigger.Default =允许目标控件确定UpdateSourceTrigger模式。
UpdateSourceTrigger.Explicit =仅在有人调用BindingExpression.UpdateSource()时更新源代码;
UpdateSourceTrigger.LostFocus =每当目标失去焦点时自动更新绑定源。这样就可以完成更改,然后在用户继续操作后更新绑定。
UpdateSourceTrigger.PropertyChanged =每当目标上的DependencyProperty更改值时,源立即更新。大多数UserControl都不默认为此属性,因为它需要更多绑定更新(可能是性能问题)。