Windows2012. 12. 27. 13:41



Implementing a Contract


Suspending과 Resuming은 생명주기 이벤트일 뿐아니라 Contract시스템의 일부로도 사용된다. 여기서는 SearchContract의 적용예를 설명할 것이다.


먼저 manifest에 선언을 하나 해주어야 한다. package.appxmanifest를 열어서 Declaration tab으로 가면 유효한 contract list가 나올것이다. Search를 선택하고 Add버튼을 눌러라. Search constract의 속서은 변경하지 않겠다.


Search contract의 목적은 시스템의 검색기능을 애플리케이션까지 확장하기 위해서이다. 여기서는 grocery list의 아이템들 중에서 검색된 첫번째 정보를 찾아줄것이다. 이는 검색을 위해서 많은 작업을 요하지 않으며 나는 ViewModel에 검색을 위핸 메서드 SearchAndSelect를 추가할 것이다.


using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.ComponentModel;

namespace MetroGrocer.Data {

  public class ViewModel : INotifyPropertyChanged {

    private ObservableCollection<GroceryItem> groceryList;

    private List<string> storeList;

    private int selectedItemIndex;

    private string homeZipCode;

    private string location;

    public ViewModel() {

      groceryList = new ObservableCollection<GroceryItem>();

      storeList = new List<string>();

      selectedItemIndex = -1;

      homeZipCode = "NY 10118";

      location = "Unknown";

}

    public void SearchAndSelect(string searchTerm) {

      int selIndex = -1;

      for (int i = 0; i < GroceryList.Count; i++) {

        if (GroceryList[i].Name.ToLower().Contains(searchTerm.ToLower())) {

          selIndex = i;

          break;

} }

      SelectedItemIndex = selIndex;

    }

// ...properties removed for brevity...
public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propName) {

      if (PropertyChanged != null) {

        PropertyChanged(this, new PropertyChangedEventArgs(propName));

} }

} }

이 메서드는 사용자가 입력한 문자열을 인자로 받아 grocery list에서 찾은 후 첫번째로 매칭된 아이템의 인덱스를 선택한다. 매치가 안되면 -1이다. SelectedItemIndex가 observable이기 때문에 아이템 검색은 그 아이넴을 선택하고 그 결과 애플리케이션 레이아웃에 선택된 아이템의 정보가 표시될것이다.

이를 위해 ListPage.xaml.cs에서 선택된 아이템으로 표시되도록 일부 수정해야 한다.


protected override void OnNavigatedTo(NavigationEventArgs e) {

  viewModel = (ViewModel)e.Parameter;

  ItemDetailFrame.Navigate(typeof(NoItemSelected));

  viewModel.PropertyChanged += (sender, args) => {

    if (args.PropertyName == "SelectedItemIndex") {

  groceryList.SelectedIndex = viewModel.SelectedItemIndex;

      if (viewModel.SelectedItemIndex == -1) {

        ItemDetailFrame.Navigate(typeof(NoItemSelected));

        AppBarDoneButton.IsEnabled = false;

      } else {

        ItemDetailFrame.Navigate(typeof(ItemDetail), viewModel);

        AppBarDoneButton.IsEnabled = true;

      }

} };

...


Contract관련 생명주기

Application class의 몇몇 메서드를 override함으로써 contract에 대응되는 생명주기 이벤트를 처리할 수 있다. 다음은 OnSearchActivated 메서드의 구현예이다. 이는 사용자가 이 앱을 타겟으로 검색할때 이 메서드가 호출된다.


using System.Threading;

using System.Threading.Tasks;

using MetroGrocer.Data;

using Windows.ApplicationModel;

using Windows.ApplicationModel.Activation;

using Windows.UI.Core;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

namespace MetroGrocer {

  sealed partial class App : Application {

    private ViewModel viewModel;

    private Task locationTask;

    private CancellationTokenSource locationTokenSource;

    private Frame rootFrame;

    public App() {

      this.InitializeComponent();

viewModel = new ViewModel();
// ...test data removed for brevity...

      this.Suspending += OnSuspending;

      this.Resuming += OnResuming;

      StartLocationTracking();

    }

    protected override void OnLaunched(LaunchActivatedEventArgs args) {

      // Create a Frame to act navigation context and navigate to the first page

      rootFrame = new Frame();

      rootFrame.Navigate(typeof(Pages.MainPage), viewModel);

      // Place the frame in the current Window and ensure that it is active

      Window.Current.Content = rootFrame;

      Window.Current.Activate();

}

protected override void OnSearchActivated(SearchActivatedEventArgs args) {

 viewModel.SearchAndSelect(args.QueryText);

}

//...other methods removed for brevity

} }


이것이 search contract를 지원하기 위한 작업의 전부이다. 

Posted by 삼스