可编辑组合框

6
我想创建可编辑的组合框,具有以下属性:
  1. 将文本属性绑定到我的数据模型。
  2. 数据模型可以覆盖GUI中的更改,即使在选择更改时也是如此。例如,我可以从1、2、3中选择2,但是在下面的某个组件中将其更改为3。
  3. 在以下事件上更新数据模型:

    1. 选择更改
    2. 失去焦点
    3. 按Enter键(应与失去焦点行为相同)。
我已经能够创建这样的控件,但它非常丑陋(使用了许多技巧),我希望有一个更简单的方法...
提前感谢。
2个回答

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();
        }
    }

}

0

最简单的方法是使用绑定上的UpdateSourceTrigger属性。您可能无法完全匹配当前的行为,但您可能会发现它是可比较的。

UpdateSourceTrigger属性控制绑定目标何时更新源。不同的WPF控件在绑定时具有不同的默认值。

以下是您的选项:

UpdateSourceTrigger.Default = 允许目标控件确定UpdateSourceTrigger模式。

UpdateSourceTrigger.Explicit = 仅在某人调用BindingExpression.UpdateSource()时更新源。

UpdateSourceTrigger.LostFocus = 每当目标失去焦点时自动更新绑定源。这样可以完成更改,然后在用户移动到下一个控件之后更新绑定。

UpdateSourceTrigger.PropertyChanged = 每当目标上的DependencyProperty更改值时,源立即更新。大多数UserControl不会默认使用此属性,因为它需要更多的绑定更新(可能会影响性能)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接