2011-03-12 4 views
3

WP7의 다른 페이지에서 저장되고 도달 할 수있는 userid와 같은 변수를 저장하는 가장 좋은 방법은 무엇입니까?변수 저장 wp7

답변

5

쿼리 스트링 방법이 있지만 구현하기에 다소 고통 스러울 수 있습니다.

탐색 할 때 HTTP 쿼리 문자열과 같은 매개 변수를 전달하십시오.

그런 다음 상대방에서 키가 있는지 확인하고 값을 추출하십시오. 이것의 단점은 만약 당신이 1보다 많은 것을 할 필요가 있다면, 당신은 직접 타이핑 할 필요가 있고 그것은 오직 문자열만을 지원해야한다는 것입니다.

정수를 전달하려면 변환해야합니다.

NavigationService.Navigate(new Uri("/PanoramaPage1.xaml?selected=item2", UriKind.Relative)); 

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
    { 
     string selected = String.Empty; 

     //check to see if the selected parameter was passed. 
     if (NavigationContext.QueryString.ContainsKey("selected")) 
     { 
      //get the selected parameter off the query string from MainPage. 
      selected = NavigationContext.QueryString["selected"]; 
     } 

     //did the querystring indicate we should go to item2 instead of item1? 
     if (selected == "item2") 
     { 
      //item2 is the second item, but 0 indexed. 
      myPanorama.DefaultItem = myPanorama.Items[1]; 
     } 
     base.OnNavigatedTo(e); 
    } 

가 여기에 쿼리 문자열을 사용하는 샘플 응용 프로그램 (그리고 복잡한 개체를 전달할 수, 당신은 당신이 다른 측면에서 다시 컴파일하는 데 필요한 모든 조각을 취할 필요). http://dl.dropbox.com/u/129101/Panorama_querystring.zip

변수를 전역 적으로 정의하거나 정적 클래스를 사용하는 것이 더 쉬운 아이디어입니다. App.xaml.cs에서, 단순히 간단하게 할 새로운 페이지에서 다음

MyComplexObject obj; 
int four = 4; 
... 

App.PageContext.Add("mycomplexobj",obj); 
App.PageContext.Add("four",four); 

을, 첫 페이지에, 그리고

using System.Collections.Generic; 

public static Dictionary<string,object> PageContext = new Dictionary<string,object>; 

을 정의

MyComplexObj obj = App.PageContext["mycomplexobj"] as MyComplexObj; 
int four = (int)App.PageContext["four"]; 

안전, 당신은 아마해야합니다 객체가 존재하는지 확인하십시오 :

if (App.PageContext.ContainsKey("four")) 
int four = (int)App.PageContext["four"]; 
+0

thnx 정말 도움이됩니다. – Arnstein

+1

+1. 'Activiated'와'Deactivated' 이벤트는'State'에이 사전 만 저장할 필요가 있기 때문에 정적 모델을 사용하기 때문에 실행 모델을보다 쉽게 ​​처리 할 수 ​​있습니다. 그러나 직렬화 가능한 객체 만 저장한다는 경고와 함께 명시 적으로 언급 한 경우이 대답이 개선 될 것입니다. – AnthonyWJones

1

App 레벨 변수 (App.xaml.cs에 정의 됨)를 사용하여 앱 내의 어느 곳에서나 액세스 할 수 있습니다. 계속 유지하려면 격리 저장소로 이동하여 App launch/activate에서 읽습니다. JSon에서 격리 저장소의 읽기/쓰기 직렬화/비 직렬화에 사용할 수있는 도우미가 있습니다.

제프의 게시물 (here)에서 절연 스토리지 사용 팁을 확인하십시오.

희망이 도움이됩니다.

1

음 "최고"그러나 나는 응용 프로그램 서비스가 이런 종류의 좋은 후보 항상 주관적인 생각한다 : - 당신은 당신의 App.xaml이의 인스턴스를 배치

public interface IPhoneApplicationService : IApplicationService 
{ 
    string Name {get; set;} 
    object Deactivating(); 
    void Activating(object state); 
} 

public class AuthenticationService : IPhoneApplicationService 
{ 
    public static AuthenticationService Current {get; private set; } 

    public void StartService(ApplicationServiceContext context) 
    { 
     Current = this; 
    } 

    public void StopService() 
    { 
     Current = null; 
    } 

    public string Name {get; set;} 

    public object Deactivating() 
    { 
     // Return an serialisable object such as a Dictionary if necessary. 
     return UserID; 
    } 

    public void Activating(object state) 
    { 
     UserID = (int)state; 
    } 

    public int UserID { get; private set; } 

    public void Logon(string username, string password) 
    { 
     // Code here that eventually assigns to UserID. 
    } 
} 

: -

을 이제
<Application.ApplicationLifetimeObjects> 
    <!--Required object that handles lifetime events for the application--> 

    <shell:PhoneApplicationService 
     Launching="Application_Launching" Closing="Application_Closing" 
     Activated="Application_Activated" Deactivated="Application_Deactivated"/> 

    <local:AuthenticationService Name="AuthServ" /> 

</Application.ApplicationLifetimeObjects> 

당신이 App.xaml.cs를 조정할 필요가 않습니다 -

private void Application_Activated(object sender, ActivatedEventArgs e) 
    { 
     var state = PhoneApplicationService.Current.State; 
     foreach (var service in ApplicationLifetimeObjects.OfType<IPhoneApplicationService>()) 
     { 
      if (state.ContainsKey(service.Name)) 
      { 
       service.Activating(state[service.Name]); 
      } 
     } 
    } 

    private void Application_Deactivated(object sender, DeactivatedEventArgs e) 
    { 
     var state = PhoneApplicationService.Current.State; 
     foreach (var service in ApplicationLifetimeObjects.OfType<IPhoneApplicationService>()) 
     { 
      if (state.ContainsKey(service.Name)) 
      { 
       state[service.Name] = service.Deactivating(); 
      } 
      else 
      { 
       state.Add(service.Name, service.Deactivating()); 
      } 
     } 
    } 

당신은 지금 당신이 앱에서 어디서나 사용자 ID에 액세스 할 수 있습니다 : -

AuthenticationService.Current.UserID 

이 일반 패턴은 주요 응용 프로그램 전체 서비스의 분리를 유지하는 데 사용할 수 있습니다 (사용자는 App 클래스에 모든 불투명 한 속성을로드하지 않습니다). 또한 필수적인 활성화 사이의 상태를 유지하기위한 고리를 제공합니다.