ValueMemberPath Binding in AutoCompleteBox WPF only returns top result in last name search?

旧巷老猫 提交于 2019-12-06 09:03:02

This is a bug in the AutoCompleteBox. Internal to the control the ValueMemberPath and ValueMemberBinding properties are implemented using a type called BindingEvaluator. This class is a FrameworkElement that the AutoCompleteBox uses to do indirect value binding.

The problem is that when a BindingEvaluator is disconnected from the logical tree, binding doesn't work. Here is how AutoCompleteBox needs to manage its BindingEvaluator in order for it to work:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DataContext = new { FirstName = "Bill", LastName = "Smith" };
    var valueBindingEvaluator = new BindingEvaluator<string>();
    AddLogicalChild(valueBindingEvaluator);
    valueBindingEvaluator.ValueBinding = new Binding("FirstName");
    var value = valueBindingEvaluator.GetDynamicValue(DataContext);
}

This is a pretty easy bug to fix if you are willing to recompile the WPF Toolkit yourself.

public Binding ValueMemberBinding
{
    get
    {
        return _valueBindingEvaluator != null ?
            _valueBindingEvaluator.ValueBinding : null;
    }
    set
    {
        if (_valueBindingEvaluator == null)
        {
            _valueBindingEvaluator = new BindingEvaluator<string>();
            AddLogicalChild(_valueBindingEvaluator);
        }
        _valueBindingEvaluator.ValueBinding = value;
    }
}

This also fixes the bug you linked to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!