可编辑的ComboBox绑定和更新源触发器

时间:2015-06-01 15:18:00

标签: c# wpf binding combobox

要求

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

}

此代码有两个问题:

  • 从下拉菜单中选择项目,然后使用以前选择的值更新来源,为什么?
  • 当用户开始输入内容然后单击下拉按钮从列表中选择内容时 - 源会再次更新(由于焦点丢失?),如何避免?

我有点害怕陷入XY problem这就是为什么我发布原始要求(也许是我错误的方向?)而不是要求帮助我解决上述问题之一。

3 个答案:

答案 0 :(得分:5)

您更新源代码以响应特定事件的方法是正确的,但您需要考虑ComboBox更新内容的方式。此外,您可能希望将UpdateSourceTrigger设置为LostFocus,以便您没有足够的更新案例来处理。

您还应该考虑将代码移动到可重复使用的附加属性,以便将来可以将其应用于其他地方的组合框。碰巧我过去曾创造过这样的财产。

/// <summary>
/// Attached properties for use with combo boxes
/// </summary>
public static class ComboBoxBehaviors
{
    private static bool sInSelectionChange;

    /// <summary>
    /// Whether the combo box should commit changes to its Text property when the Enter key is pressed
    /// </summary>
    public static readonly DependencyProperty CommitOnEnterProperty = DependencyProperty.RegisterAttached("CommitOnEnter", typeof(bool), typeof(ComboBoxBehaviors),
        new PropertyMetadata(false, OnCommitOnEnterChanged));

    /// <summary>
    /// Returns the value of the CommitOnEnter property for the specified ComboBox
    /// </summary>
    public static bool GetCommitOnEnter(ComboBox control)
    {
        return (bool)control.GetValue(CommitOnEnterProperty);
    }

    /// <summary>
    /// Sets the value of the CommitOnEnterProperty for the specified ComboBox
    /// </summary>
    public static void SetCommitOnEnter(ComboBox control, bool value)
    {
        control.SetValue(CommitOnEnterProperty, value);
    }

    /// <summary>
    /// Called when the value of the CommitOnEnter property changes for a given ComboBox
    /// </summary>
    private static void OnCommitOnEnterChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        ComboBox control = sender as ComboBox;
        if (control != null)
        {
            if ((bool)e.OldValue)
            {
                control.KeyUp -= ComboBox_KeyUp;
                control.SelectionChanged -= ComboBox_SelectionChanged;
            }
            if ((bool)e.NewValue)
            {
                control.KeyUp += ComboBox_KeyUp;
                control.SelectionChanged += ComboBox_SelectionChanged;
            }
        }
    }

    /// <summary>
    /// Handler for the KeyUp event attached to a ComboBox that has CommitOnEnter set to true
    /// </summary>
    private static void ComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        ComboBox control = sender as ComboBox;
        if (control != null && e.Key == Key.Enter)
        {
            BindingExpression expression = control.GetBindingExpression(ComboBox.TextProperty);
            if (expression != null)
            {
                expression.UpdateSource();
            }
            e.Handled = true;
        }
    }

    /// <summary>
    /// Handler for the SelectionChanged event attached to a ComboBox that has CommitOnEnter set to true
    /// </summary>
    private static void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!sInSelectionChange)
        {
            var descriptor = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));
            descriptor.AddValueChanged(sender, ComboBox_TextChanged);
            sInSelectionChange = true;
        }
    }

    /// <summary>
    /// Handler for the Text property changing as a result of selection changing in a ComboBox that has CommitOnEnter set to true
    /// </summary>
    private static void ComboBox_TextChanged(object sender, EventArgs e)
    {
        var descriptor = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));
        descriptor.RemoveValueChanged(sender, ComboBox_TextChanged);

        ComboBox control = sender as ComboBox;
        if (control != null && sInSelectionChange)
        {
            sInSelectionChange = false;

            if (control.IsDropDownOpen)
            {
                BindingExpression expression = control.GetBindingExpression(ComboBox.TextProperty);
                if (expression != null)
                {
                    expression.UpdateSource();
                }
            }
        }
    }
}

以下是在xaml中设置属性的示例:

<ComboBox IsEditable="True" ItemsSource="{Binding Items}" Text="{Binding SelectedItem, UpdateSourceTrigger=LostFocus}" local:ComboBoxBehaviors.CommitOnEnter="true" />

我认为这会给你你想要的行为。您可以随意使用它,也可以根据自己的喜好进行修改。

行为实施存在一个问题,如果您开始输入现有值(并且不要按Enter键),然后从下拉列表中选择相同的值,则在此情况下源不会更新按Enter键,更改焦点或选择其他值。我确信这可以解决,但由于这不是一个正常的工作流程,因此花时间在我身上是不够的。

答案 1 :(得分:1)

我建议保留UpdateSourceTrigger=PropertyChanged,并对组合框施加延迟,以帮助缓解昂贵的setter / update问题。延迟将导致PropertyChanged事件等待您在触发前指定的毫秒数。

有关延迟的详情:http://www.jonathanantoine.com/2011/09/21/wpf-4-5-part-4-the-new-bindings-delay-property/

希望有人会为您提供更好的解决方案,但这至少应该让您继续前进。

答案 2 :(得分:0)

我有一个类似的问题,我在.cs代码中处理它。它不是XAML方式,但它完成了它。首先,我打破了绑定,然后双向手动传播值。

<ComboBox x:Name="Combo_MyValue" 
                      ItemsSource="{Binding Source={StaticResource ListData}, XPath=MyContextType/MyValueType}"
                      DisplayMemberPath="@Description"
                      SelectedValuePath="@Value"
                      IsEditable="True"
                      Loaded="Combo_MyValue_Loaded"
                      SelectionChanged = "Combo_MyValue_SelectionChanged"
                      LostFocus="Combo_MyValue_LostFocus"
                      />


    private void Combo_MyValue_Loaded(object sender, RoutedEventArgs e)
    {
        if (DataContext != null)
        {
            Combo_MyValue.SelectedValue = ((MyContextType)DataContext).MyValue;
        }
    }

    private void Combo_MyValue_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if( e.AddedItems.Count == 0)
        {
            // this is a custom value, we'll set it in the lost focus event
            return;
        }
        // this is a picklist value, get the value from itemsource
        XmlElement selectedItem = (XmlElement)e.AddedItems[0];
        string selectedValue = selectedItem.GetAttribute("Value");
        ((PumpParameters)DataContext).MyValue = selectedValue;
    }

    private void Combo_MyValue_LostFocus(object sender, RoutedEventArgs e)
    {
        if( Combo_MyValue.IsDropDownOpen || Combo_MyValue.SelectedIndex != -1)
        {
            // not a custom value
            return; 
        }
        // custom value
        ((MyContextType)DataContext).MyValue = Combo_MyValue.Text;
    }