I have been using AutoCompleteBox in the WPF Toolkit and it just about meets all my needs, all except this troublesome ValueMemberPath
binding. This is the value that the suggest box will auto complete by.
So I have this last name field, and when a user starts typing in a last name, I dynamically retrieve the top 10 results based on that. However, if the user types in 'Smith' and selects say the 4th name in the list, it always retrieves the first result in the suggestion list, because ValueMemberPath
is set to filter by LastName
. It always just thinks "Smith" is the first result even if there are 50 smiths with different first names.
I have been wracking my brain trying to figure out how to incorporate first name with this property. I tried to change ValueMemberPath
to be a FullName
field that equaled lastname, and firstname. The suggest box stops sorting as soon as a comma is entered, or if it is firstname 'space' lastname that doesn't work either.
I also ran into problems with ValueMemberPath
because this value can't be changed dynamically, and there is bug where it is null while debugging: AutoCompleteBox Bug : ValueMemberPath is Null.
I understand if no one has a complete solution. I just thought I would ask the question in case people run into this in the future and am not sure how to handle this.
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.
来源:https://stackoverflow.com/questions/4648527/valuememberpath-binding-in-autocompletebox-wpf-only-returns-top-result-in-last-n