【发布时间】:2013-08-15 00:14:45
【问题描述】:
我正在尝试使用 WPF 工具包中的 AutoCompleteBox 构建搜索字段。 AutoCompleteBox 的 Text 属性绑定到实现 INotifyPropertyChanged 的 ViewModel 中的一个属性。当属性发生变化时,它会获取新的建议以显示给用户。
如果用户在选择一个之前使用箭头键扫描自动完成建议列表,则会出现问题 - 光标移动到弹出窗口的那一刻,SelectionChanged 被触发,文本字段获得一个新值,并且自动完成建议被重新收集。这也妨碍了我使用SelectionChanged 事件开始搜索的愿望。
有什么方法可以防止在键盘导航时触发 SelectionChanged 事件?
这就是我的设置方式。注意sc:SearchField 是AutoCompleteBox 的子类,它只提供一种访问AutoCompleteBox 上的TextBox 属性的方法,因此我可以调用SelectAll() 之类的函数
XAML:
<sc:SearchField x:Name="SearchField" DataContext="{Binding SearchBoxVm}" Text="{Binding Query, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding QuerySuggestions, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" IsTextCompletionEnabled="False" Margin="54,10,117,67" Grid.RowSpan="2" BorderThickness="0" FontSize="14" PreviewKeyUp="searchField_OnKeyup" Foreground="{Binding Foreground, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontStyle="{Binding QueryFont, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
</sc:SearchField>
视图模型:
void GetQuerySuggestions()
{
if (!string.IsNullOrEmpty(Query) && !Query.Equals(DEFAULT_TEXT))
{
QueryFont = FontStyles.Normal;
Foreground = Brushes.Black;
QuerySuggestions = SearchAssistant.GetQueryRecommendations(_query);
}
}
public string _query = DEFAULT_TEXT;
public string Query
{
get
{
return _query;
}
set
{
_query = value;
GetQuerySuggestions();
NotifyPropertyChanged("Query");
}
}
List<string> querySuggestions = new List<string>();
public List<string> QuerySuggestions
{
get { return querySuggestions; }
set
{
querySuggestions = value;
NotifyPropertyChanged("QuerySuggestions");
}
}
SearchField 子类:
public class SearchField : AutoCompleteBox
{
public TextBox TextBox
{
get
{
return (this.GetTemplateChild("Text") as TextBox);
}
}
}
【问题讨论】:
标签: wpf xaml autocomplete wpftoolkit selectionchanged