2016-01-05 12 views
5

Ich rufe den QuerySubmitted-Befehl des AutoSuggestBox-Steuerelements in UWP auf. Der Befehl bindet an ICommand im Ansichtsmodell. Das Problem ist, dass AutoSuggestBoxQuerySubmittedEventArgs akzeptiert werden muss, was eine reine Benutzeroberfläche ist und in MVVM nicht akzeptabel ist.UWP Bindung an AutoSuggestBox in MVVM

mein Code sieht wie folgt aus:

<AutoSuggestBox Name="SearchAutoSuggestBox" 
       PlaceholderText="Search by keywords" 
       QueryIcon="Find" 
       > 
    <interactivity:Interaction.Behaviors> 
     <core:EventTriggerBehavior EventName="QuerySubmitted"> 
      <core:InvokeCommandAction Command="{x:Bind ViewModel.SearchCommand}" /> 
     </core:EventTriggerBehavior> 
    </interactivity:Interaction.Behaviors> 
</AutoSuggestBox> 

und meiner Meinung nach Modell sieht wie folgt aus:

public DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs> SearchCommand { get; } 

public MainPageViewModel() 
{ 
    SearchCommand = new DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs>(ExecuteMethod); 
} 

private void ExecuteMethod(AutoSuggestBoxQuerySubmittedEventArgs o) 
{ 
    // CODE HERE 
} 

ofcours AutoSuggestBoxQuerySubmittedEventArgs in der View-Modell nicht akzeptabel ist. auf der Suche nach Alternativen ... das gleiche geht zu SuggestionChouses ...

+0

M Die SDN-Seite für EventTriggerBehavior besagt, dass nur eine Teilmenge von Ereignissen unterstützt wird und QuerySubmitted keine davon ist. Haben Sie ein neues Verhalten implementiert, damit dies funktioniert? –

Antwort

8

InvokeCommandAction hat einen Parameter InputConverter, die Sie verwenden können, benannt um die Ereignisargumente in einen anderen Parameter zu konvertieren, der an Ihr ViewModel übergeben werden kann.

zunächst eine IValueConverter Klasse erstellen zu extrahieren, was Sie von Ihren Event args wie diese benötigen: -

public class AutoSuggestQueryParameterConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
     { 
      // cast value to whatever EventArgs class you are expecting here 
      var args = (AutoSuggestBoxQuerySubmittedEventArgs)value; 
      // return what you need from the args 
      return (string)args.ChosenSuggestion; 
     } 
} 

dann, dass Konverter in Ihrem XAML wie folgt verwenden:

<Page.Resources> 
    <converters:AutoSuggestQueryParameterConverter x:Key="ArgsConverter" /> 
</Page.Resources> 

<AutoSuggestBox Name="SearchAutoSuggestBox" 
      PlaceholderText="Search by keywords" 
      QueryIcon="Find"> 
    <interactivity:Interaction.Behaviors> 
     <core:EventTriggerBehavior EventName="QuerySubmitted"> 
     <core:InvokeCommandAction 
       Command="{x:Bind ViewModel.SearchCommand}" 
       InputConverter="{StaticResource ArgsConverter}" /> 
     </core:EventTriggerBehavior> 
    </interactivity:Interaction.Behaviors> 
</AutoSuggestBox> 

schließlich in Ihrem Viewmodel Ändern Sie Ihren Befehl, um eine Zeichenfolge als Parameter zu akzeptieren.So würden Sie die folgenden in Ihrem vm haben:

public DelegateCommand<string> SearchCommand { get; } 

public MainPageViewModel() 
{ 
    SearchCommand = new DelegateCommand<string>(ExecuteMethod); 
} 

private void ExecuteMethod(string o) 
{ 
    // CODE HERE 
} 
+0

Yup, das ist die richtige Antwort. Vielen Dank :) – kaycee

1

Wenn es Ihnen nichts ausmacht zu tun non pure MVVM Weg.

MainPage.xaml:

<AutoSuggestBox Name="SearchAutoSuggestBox" 
     PlaceholderText="Search by keywords" 
     QueryIcon="Find" QuerySubmitted="{x:Bind ViewModel.SearchQuerySubmitted}" IsEnabled="{x:Bind ViewModel.CanExecuteSearchCommand, Mode=TwoWay}" 
     > 
</AutoSuggestBox> 

MainPageViewModel.cs:

public class MainPageViewModel : INotifyPropertyChanged 
{ 
    private bool _canExecuteSearchCommand; 

    public MainPageViewModel() 
    { 
     this.CanExecuteSearchCommand = true; 
    } 

    public bool CanExecuteSearchCommand 
    { 
     get { return _canExecuteSearchCommand; } 
     set 
     { 
      bool changed = _canExecuteSearchCommand != value; 
      _canExecuteSearchCommand = value; 

      if(changed) 
       this.OnPropertyChanged(); 
     } 
    } 

    public void SearchQuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) 
    { 
     // Just example disabling SearchBox 
     this.CanExecuteSearchCommand = false; 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

MainPage.cs:

MainPageViewModel ViewModel = new MainPageViewModel(); 
2

Sie können den Suchtext (Text-Eigenschaft) binden an eine Ansicht Modelleigenschaft und die Ereignisse parameterlose Methoden. Auf diese Weise der View-Modell gewohnt haben, um mit UI-Objekte behandeln:

XAML:

<AutoSuggestBox Header="What's your name?" 
       TextChanged="{x:Bind ViewModel.FilterUsuals}" 
       QuerySubmitted="{x:Bind ViewModel.ProcessQuery}" 
       SuggestionChosen="{x:Bind ViewModel.ProcessChoice}" 
       ItemsSource="{x:Bind ViewModel.Usuals, Mode=OneWay}" 
       Text="{x:Bind ViewModel.SearchText, Mode=TwoWay}" 
       QueryIcon="Find" /> 

-Code hinter:

public class MainPageViewModel : SomeViewModelBaseClass 
{ 
    /* Boilerplate code and constructor not included */ 

    private string _SearchText; 
    public string SearchText {/* getter and setter INotyfyPropertyChange compliant */ } 

    private List<string> _Usuals; // Initialized on constructor 
    public string Usuals {/* getter and setter INotyfyPropertyChange compliant */ } 


    public void FilterUsuals() 
    { 
     // the search string is in SearchText Example: 
     Usuals = _UsualsStore.Where(u => u.Contains(_SearchText.ToLower())).ToList(); 
    } 

    public void ProcessQuery() { /* TODO - search string is in SearchText */ } 

    public void ProcessChoice() { /* TODO - search string is in SearchText */ } 
} 
0

UWP Command/Delegate zu AutoSuggestBox Bindung in MVVM

Für UWP Mobile Application

Machen Sie eine DelegateCommand Klasse

public class DelegateCommand<T> : ICommand 
{ 
    private readonly Action<T> executeAction; 
    Func<object, bool> canExecute; 

    public event EventHandler CanExecuteChanged; 

    public DelegateCommand(Action<T> executeAction) 
     : this(executeAction, null) 
    { 
     //var a = ((Page)(((Func<object, bool>)(executeAction.Target)).Target)).Name; 
     //((ViewModel.VMBranchSelection)(executeAction.Target)).; 

    } 

    public DelegateCommand(Action<T> executeAction, Func<object, bool> canExecute) 
    { 
     this.executeAction = executeAction; 
     this.canExecute = canExecute; 
    } 

    public bool CanExecute(object parameter) 
    { 
     return canExecute == null ? true : canExecute(parameter); 
    } 

    public void Execute(object parameter) 
    { 
     executeAction((T)parameter); 
    } 
    public void RaiseCanExecuteChanged() 
    { 
     EventHandler handler = this.CanExecuteChanged; 
     if (handler != null) 
     { 
      handler(this, new EventArgs()); 
     } 
    } 
} 

In Ansicht Modell

public ICommand SuggessionSelectCity_QuerySubmitted 
    { 
     get { return new DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs>(this.SuggessionSelectCityQuerySubmitted); } 
    } 

    private void  SuggessionSelectCityQuerySubmitted(AutoSuggestBoxQuerySubmittedEventArgs obj) 
    { 
     if (obj.ChosenSuggestion != null) 
     { 
      AutosuggestionTextBoxName.Text = ((ModelName) (obj.ChosenSuggestion)).Model's Property name; 
//or 
AutosuggestionTextBoxName.Text =(obj.ChosenSuggestion).property name  
     } 
     else 
     { 

     } 
    } 

In XAML-Code

<AutoSuggestBox Grid.Column="1" x:Name="SuggessionSelectCity" 
      PlaceholderText="Search by keywords" QueryIcon="Find" 
      ItemsSource="{Binding PApplicantCityList}" 

      HorizontalAlignment="Center" VerticalAlignment="Center" DisplayMemberPath="Description" Width="250" Height="45"> 

       <Interactivity:Interaction.Behaviors> 
        <Core:EventTriggerBehavior EventName="TextChanged"> 
         <Core:EventTriggerBehavior.Actions> 
          <Core:InvokeCommandAction Command="{Binding SuggessionSelectCityTextChange}"/> 
         </Core:EventTriggerBehavior.Actions> 
        </Core:EventTriggerBehavior> 

        <Core:EventTriggerBehavior EventName="QuerySubmitted"> 
         <Core:EventTriggerBehavior.Actions> 
          <Core:InvokeCommandAction Command="{Binding SuggessionSelectCity_QuerySubmitted}"/> 
         </Core:EventTriggerBehavior.Actions> 
        </Core:EventTriggerBehavior> 

        <Core:EventTriggerBehavior EventName="SuggestionChosen"> 
         <Core:EventTriggerBehavior.Actions> 
          <Core:InvokeCommandAction Command="{Binding SuggessionSelectCitySuggestionChosen}"/> 
         </Core:EventTriggerBehavior.Actions> 
        </Core:EventTriggerBehavior> 


       </Interactivity:Interaction.Behaviors> 
      </AutoSuggestBox> 
     </Grid> 

Erstellen Sie eine Liste in Ansicht Modell für Autosuggestion TextBox Itemssource

private ObservableCollection<ResultMasterModel> ApplicantCityList; 
    public ObservableCollection<ResultMasterModel> PApplicantCityList 
    { 
     get { return ApplicantCityList; } 
     set { this.SetProperty(ref this.ApplicantCityList, value); } 
    } 

erstellen Modell im Modellordner einige harte Codewert in oben aufgeführte Liste hinzufügen

public class ResultMasterModel 
{ 
    public string Code { get; set; } 
    public string Description { get; set; } 
}