I am currently using this AutoCompleteTextBox
in my project: WPFTextBoxAutoComplete
I am binding the TextBox to a List<string>
of Employee names. I am doing this like so;
<TextBox
Width="250" Height="50" HorizontalAlignment="Center"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding Employees}"
/>
What I want the TextBox
to do is offer a suggestion when the user types in an Employee's name. However, no suggestion appears at all, which leads me to believe that I am not binding the UpdateSourceTrigger
properly.
If I am only binding the behaviour to a List<string>
then how does the Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
work when there is no property of the Employee's name? I am a little unsure as to what needs to change to trigger the update source.
The website provides this explanation: Now, every time the "TestText" property of your datacontext is changed, WPFTextBoxAutoComplete will provide you with auto-completion suggestions.
However, I don't believe my DataContext
has a "Name" property.
EDIT:
/**** AutoComplete ****/
public static readonly DependencyProperty AutoCompleteTest = DependencyProperty.Register(
"Test", typeof(string), typeof(CompanyManagement), new PropertyMetadata(default(string)));
public string Test
{
get { return (string)GetValue(AutoCompleteTest); }
set { SetValue(AutoCompleteTest, value); }
}
TextBox XAML
<TextBox
Width="250" Height="50" HorizontalAlignment="Center"
Text="{Binding Test, UpdateSourceTrigger=PropertyChanged}"
behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding Employees}"
/>
You just need a property called Name
in your DataContext
with change notification (either with DependencyProperty
or INotifyPropertyChanged
).
With DependencyProperty
:
public static readonly DependencyProperty NameProperty = DependencyProperty.Register(
"Name", typeof (string), typeof (WhateverClassYouHave), new PropertyMetadata(default(string)));
public string Name
{
get { return (string) GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
With INotifyPropertyChanged
:
public class WhateverClassYouHave: INotifyPropertyChanged
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged(nameof(Name)); // C# 6 feature
}
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); // C# 6 feature
}
As you type, the Name
property will change, notify the behavior about the change and it will offer you the suggestion.
Result: