2016-01-05 16 views
5

tôi đang gọi lệnh QuerySubmitted của điều khiển AutoSuggestBox trong UWP. lệnh liên kết với ICommand trong mô hình khung nhìn. vấn đề là nó đòi hỏi phải chấp nhận AutoSuggestBoxQuerySubmittedEventArgs đó là giao diện người dùng thuần túy và nó không được chấp nhận trong MVVM.UWP Liên kết với AutoSuggestBox trong MVVM

mã của tôi trông như thế:

<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> 

và mô hình quan điểm của tôi trông như thế:

public DelegateCommand<AutoSuggestBoxQuerySubmittedEventArgs> SearchCommand { get; } 

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

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

ofcours AutoSuggestBoxQuerySubmittedEventArgs là không thể chấp nhận được trong mô hình xem. tìm kiếm các lựa chọn thay thế ... giống với SuggestionChosen ...

+0

M Trang SDN cho EventTriggerBehavior nói rằng chỉ có một tập con của các sự kiện được hỗ trợ và QuerySubmitted không phải là một trong số chúng. Bạn đã thực hiện một hành vi mới cho việc này để làm việc? –

Trả lời

8

InvokeCommandAction có một tham số tên InputConverter mà bạn có thể sử dụng để chuyển đổi sự kiện này thành một số tham số khác có thể được chuyển tới ViewModel của bạn.

Đầu tiên tạo ra một lớp IValueConverter để trích xuất những gì bạn cần từ args sự kiện của bạn như thế này: -

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; 
     } 
} 

Sau đó sử dụng chuyển đổi mà trong XAML của bạn như thế này:

<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> 

Cuối cùng trong viewmodel của bạn thay đổi lệnh của bạn để chấp nhận một chuỗi như tham số.Vì vậy, bạn sẽ có sau trong vm của bạn:

public DelegateCommand<string> SearchCommand { get; } 

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

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

yup đó là câu trả lời đúng. cảm ơn :) – kaycee

1

Nếu bạn không nhớ làm cách non pure MVVM.

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

Bạn có thể liên kết chuỗi tìm kiếm (thuộc tính Text) để sở hữu một cái nhìn mô hình và các sự kiện các phương thức không tham số. Bằng cách này, mô hình xem sẽ không phải đối phó với các đối tượng giao diện người dùng:

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" /> 

Mã đằng sau:

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 Binding Command/Delegate để AutoSuggestBox trong MVVM

Đối UWP ứng dụng di động

Tạo một lớp DelegateCommand

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()); 
     } 
    } 
} 

Trong Xem các mẫu

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 
     { 

     } 
    } 

Trong XAML Mã

<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> 

Tạo danh sách trong Xem Mô hình tự kỷ ám thị TextBox ItemsSource

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

thêm một số giá trị mã cứng trong danh sách

trên Tạo một mô hình trong mô hình thư mục

public class ResultMasterModel 
{ 
    public string Code { get; set; } 
    public string Description { get; set; } 
} 
Các vấn đề liên quan