2015-08-13 62 views
2

我目前正在開發UWP應用程序。UWP EventTriggerBehaviour命令未調用

我有一個AutoSuggestBox控件,我想用命令處理它的一些事件(因爲我遵循MVVM模式)。爲此,我引用了Microsoft.Xaml.Interactivity(來自Blend)。

我正在使用的代碼是這樣:

 <AutoSuggestBox x:Name="autoSuggestBox" 
          Width="256" 
          HorizontalAlignment="Right" 
          ItemsSource="{Binding SearchResults}" 
          MaxSuggestionListHeight="256" 
          QueryIcon="Find"> 
       <i:Interaction.Behaviors> 
        <core:EventTriggerBehavior EventName="SuggestionChosen"> 
         <core:InvokeCommandAction Command="{Binding SuggestionChosenCommand}" CommandParameter="{Binding ElementName=autoSuggestBox}" /> 
        </core:EventTriggerBehavior> 
        <core:EventTriggerBehavior EventName="TextChanged"> 
         <core:InvokeCommandAction Command="{Binding ChangeSearchResultsCommand}" CommandParameter="{Binding Text, ElementName=autoSuggestBox}" /> 
        </core:EventTriggerBehavior> 
       </i:Interaction.Behaviors> 
       <AutoSuggestBox.ItemTemplate> 
        ... 
       </AutoSuggestBox.ItemTemplate> 
      </AutoSuggestBox> 

而在視圖模型的背後,我定義我的命令,例如:

Command<string> _changeSearchResultsCommand = default(Command<string>); 
    public Command<string> ChangeSearchResultsCommand { get { return _changeSearchResultsCommand ?? (_changeSearchResultsCommand = new Command<string>(async (param) => { await ExecuteChangeSearchResultsCommand(param); }, CanExecuteChangeSearchResultsCommand)); } } 
    private bool CanExecuteChangeSearchResultsCommand(string p) { return !IsSearchBusy; } 
    private async Task ExecuteChangeSearchResultsCommand(string text) 
    { 
     ... 
    } 

    Command<ShowModel> _suggestionChosenCommand = default(Command<ShowModel>); 
    public Command<ShowModel> SuggestionChosenCommand { get { return _suggestionChosenCommand ?? (_suggestionChosenCommand = new Command<ShowModel>(async (param) => { await ExecuteSuggestionChosenCommand(param); }, CanExecuteSuggestionChosenCommand)); } } 
    private bool CanExecuteSuggestionChosenCommand(ShowModel p) { return true; } 
    public async Task ExecuteSuggestionChosenCommand(ShowModel show) 
    { 
     ... 
    } 

而且SearchResult所定義是這樣的:

private ObservableCollection<ShowModel> _searchResults = default(ObservableCollection<ShowModel>); 
    public ObservableCollection<ShowModel> SearchResults { get { return _searchResults; } set { Set(ref _searchResults, value); } } 

我的問題是'TextChanged'事件正常工作。每當事件觸發時都會調用該命令。但是,SuggestionChosen事件從不會觸發命令。如果我將SuggestionChosen事件直接附加到控件上,它會觸發,但我希望命令被調用。這兩個事件的代碼大致相同,所以我似乎無法弄清楚爲什麼要被調用而不是其他調用。

回答

3

我設法自己解決這個問題。問題在於SuggestionChosen事件綁定。該綁定沒有返回該命令期望的值的類型(ShowModel)。

我所做的是將命令類型更改爲AutoSuggestBoxSuggestionChosenEventArgs,並且未在XAML中傳遞任何命令參數。該命令是以參數作爲參數調用的,我甚至可以從參數中訪問選定的項目。

+0

除了在TextChanged事件上調用命令,您可以在雙向模式下綁定ViewModel中的查詢字符串屬性,並且在Query屬性的設置器中,您可以更新SuggestionsObservableCollection。這將是一個更好的MVVM方法。 – artfuldev