gpt4 book ai didi

wpf - 可编辑组合框

转载 作者:行者123 更新时间:2023-12-04 15:49:30 30 4
gpt4 key购买 nike

我想创建具有以下属性的可编辑组合框:

  • 将文本属性绑定(bind)到我的数据模型。
  • 数据模型可能会覆盖 GUI 中的更改,即使在选择更改时也是如此。例如。我可以从 1、2、3 中选择 我选择 2,但是下面的某些组件将其更改为 3。
  • 更新以下事件的数据模型:
  • 选择已更改
  • 失去焦点
  • 按下 Enter(应该与失去焦点的行为相同)。

  • 我已经能够创建这样的控件,但它非常丑陋(使用许多黑客),我希望有一个更简单的方法......

    提前致谢

    最佳答案

    好的,这就是我所做的,它并没有那么难看:

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

    }

    关于wpf - 可编辑组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/582232/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com