Autocompletebox doesn't clear keyboard strokes

2019-07-24 15:36发布

问题:

In an application of mine, I'm using the WPF autocomplete box from the wpf toolkit. I'm implementing it via the MVVM pattern. The binding works fine, but I have a small problem when trying to clear the content of the autocompletebox. Setting the bound property in the viewmodel to null, clears the text only partially (all text entered via the keyboard is not cleared - i.e. if I enter CH when fetching all the cities and select Chicago and the set the bound property to null, the CH is not being cleared , the rest ICAGO is.)

The XAML looks like this:

           <my:AutoCompleteBox Grid.Row="0"
                                Grid.Column="1" 
                                HorizontalAlignment="Left" 
                                Margin="0,6,0,0" 
                                Name="acTown" 
                                SelectedItem="{Binding NewTown, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                ValueMemberBinding="{Binding Converter={StaticResource TownConverter}}"        
                                Populating="Populating"
                                VerticalAlignment="Top" 
                                Height="Auto" 
            </my:AutoCompleteBox>

The method in the viewmodel to clear the box is:

   public void ClearTown()
    {

    NewTown = null;

    OnPropertyChanged("NewTown");
}

I can't figure out what's wrong with the code, or is this just a bug in the autocompletebox?

After extensive research, I found this article: How do you clear the Silverlight AutoCompleteBox SearchText using MVVM, but it does not offer a solution. There seems to be a SearchText property on the AutoCompleteBox that is readonly and cannot have a setter

回答1:

Finally got it. If anyone's interested, the solution is to simply change NewTown = null to NewTown = new NewTown() in the ClearTown function.