2013-10-19 2 views
2

내 문제는 내보기와 데이터간에 바인딩을 사용하지만 처음부터 다시 데이터를 업데이트하면 내보기가 업데이트되지 않습니다. (윈도우 폰 8)Xaml C# 바인딩 데이터는 처음에만 작동합니다.

보기 코드 :

<phone:LongListSelector x:Name="DataContextAction" DataContext="{Binding DataContextAction}" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="665" Margin="10,10,0,0" VerticalAlignment="Top" Width="471"> 
     <phone:LongListSelector.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Margin="{StaticResource PhoneMargin}"> 
        <TextBlock Text="{Binding HardwareId}" Style="{StaticResource PhoneTextLargeStyle}"/> 
        <TextBlock Text="{Binding Type}" Style="{StaticResource PhoneTextNormalStyle}"/> 
        <TextBlock Text="{Binding Status}" Style="{StaticResource PhoneTextNormalStyle}"/> 
       </StackPanel> 
      </DataTemplate> 
     </phone:LongListSelector.ItemTemplate> 
    </phone:LongListSelector> 

xaml.cs 페이지 : 나는 새로운 행동을 시작할 때를 업데이트 할

public DevicePage() 
{ 
    InitializeComponent(); 

    // Display message waiting before make the http query. 
    txtMessage.Foreground = new SolidColorBrush(Colors.Orange); 
    txtMessage.Text = "Loading..."; 

    // Initialize the view data binding. 
    InitializeAsynch(); 

    // Start new thread in background. 
    var refreshViewBackground = new System.Threading.Thread(RefreshViewBackground); 
    refreshViewBackground.Start(); 
} 

private async void InitializeAsynch() 
{ 
    // TODO BAD CODE but I don't understand (and I don't have enough time) how make it better. http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html 
    DataContext = await UserSession.RefreshLastLocationDevices(); 
    // If I do that now with empty session, the view will be empty. 
    //DataContextAction.ItemsSource = UserSession.Actions; 
    txtMessage.Text = ""; 
} 

내가 새 스레드를 실행 세션이 완료 될 때까지 기다립니다. (이전 코드와 동일한 파일에 있음)

private void StartListenNewAction(DataAction action, DataDevice device) 
{ 
    // Update the actions list; 
    try 
    { 
     DataContextAction.ItemsSource = UserSession.Actions; 
    } 
    catch (Exception e) 
    { 
     Debug.WriteLine("Unable to refresh, another thread has updated the action list. " + e.Message); 
    } 

    // Start new thread in background for this specific action. 
    ParameterizedThreadStart refreshActionBackground = new ParameterizedThreadStart(RefreshActionBackground); 
    Thread thread = new Thread(refreshActionBackground); 
    Thread.Start(new object[] { action, device }); 
} 

하지만 여기서는 처음으로 작동합니다. 내보기는 한 번만 업데이트됩니다. 도움을 주셔서 감사합니다. 이해할 수 없습니다. 다른 longListSelector를 사용하고 세션을 사용하는 데 문제가 없지만 직접 {바인딩}이라는 이름을 사용합니다.

<phone:LongListSelector x:Name="listDevices" ItemsSource="{Binding}" ... 

그래서 여기서는 왜 작동하지 않는지 이해할 수 없습니다.

편집 : 으로 질문 :

// Refresh only one action in background. 
public async void RefreshActionBackground(object args) 
{ 
    bool pending = true; 

    DataAction action = (DataAction)((object[])args)[0]; 
    DataDevice device = (DataDevice)((object[])args)[1]; 

    while (pending) 
    { 
     // Sleep some time. 
     System.Threading.Thread.Sleep(device.AskingFrequencyActive * 1000); 

     // Get the action from the web service. 
     List<Param> parameters = new List<Param>(); 
     parameters.Add(new Param("email", UserSession.Email)); 
     parameters.Add(new Param("password", UserSession.Password)); 
     parameters.Add(new Param("hardwareId", device.HardwareId));// Mandatory. 
     parameters.Add(new Param("id", action.Id)); 
     parameters.Add(new Param("limit", "1")); 

     // Send the request. 
     IDictionary<string, object> response = await WebService.Send("action", "find", parameters); 

     if ((bool)response["status"]) 
     { 
      // Get objects from the response. 
      Dictionary<string, object> data = (Dictionary<string, object>)response["data"]; 
      // We got an array, convert to array. 
      JsonArray actionsArray = (JsonArray)data["action"]; 

      // Update the session. 
      actionsArray.ForEach(delegate(dynamic actionJson) 
      { 
       // Update the action from the session. 
       UserSession.Actions.Where(s => (string)s.Id == (string)actionJson["id"]).First().Status = (string)actionJson["status"]; 

       // Get the action from the session. 
       DataAction actionSession = UserSession.Actions.Where(s => s.Id == action.Id).First(); 

       // Compare to the session which could be updated since the last time. 
       if (actionSession.Status == "Executed") 
       { 
        pending = false; 
        // Update UI thread. 
        Deployment.Current.Dispatcher.BeginInvoke(() => 
        { 
         // Update the actions list; 
         try 
         { 
          DataContextAction.ItemsSource = UserSession.Actions; 
         }catch(Exception e){ 
          Debug.WriteLine("Unable to refresh, another thread has updated the action list. " + e.Message); 
         } 

         // Update UI interface. 
         txtMessage.Foreground = new SolidColorBrush(Colors.Green); 
         this.txtMessage.Text = "Action executed: " + action.Type; 
        }); 
       } 
      }); 

     } 
     else 
     { 
      Debug.WriteLine((string)response["message"]); 
     } 
    } 
} 
+1

나는 이것을 읽을 것을 제안하겠다 - About InotifyPropertyChanged http://www.codeproject.com/Articles/41817/Implementing-INotifyPropertyChanged –

+0

'RefreshActionBackground '와'RefreshViewBackground'는 어디에 정의되어 있는가? 보여줄 수 있습니까? –

+0

메인 게시물이 업데이트되었습니다. RefreshActionBackground 함수가 추가되었습니다. – Vadorequest

답변

0

내가 말했듯이 프로젝트는 끝났지 만 실제로 어떻게 작동하는지, 실제로는 절대적으로 미친 방법을 찾아 냈습니다.

내 listview가 두 개 이상의 장치를 유지하는 경우 매우 간단합니다. 작동합니다. 하나만 있으면 작동하지 않습니다. 무슨 일이 벌어지고 있는지 나는 전혀 모른다. 그래서 더 이상 일하지 않는다. 그래서 그것은 속임수 일 것이다. 아마도 다른 누군가에게 일어날 것이다.

이 프로젝트는 여기에, 자식에 호스팅 :

https://bitbucket.org/Vadorequest/trip-analyzer-server-node.js/overview 당신의 도움에 감사드립니다.

0

난 당신이 새 스레드를 사용하지한다고 생각합니다. 기본적으로 시스템에 문제가 생길 때까지는 아무런 이유없이 새 스레드를 요구합니다. 대신 Tasks을 사용하십시오. 사용자 인터페이스가 업데이트 될 예정인 두 번째 시간에도 여전히 올바른 스레드를 사용하고 있습니까?

+1

RefreshActionBackground() 함수에서 Deployment.Current.Dispatcher.BeginInvoke를 사용하여 UI 스레드를 업데이트하는 코드를 실행하므로 좋다고 생각합니다. StartListenNewAction() 함수에서 나는 UI 스레드에 있어요. 나는 그것을 어떻게해서든지 시험 할 것이다. 나는 Tasks에 관해 모른다, 나는 그들을 기다린다. 난 정말 응용 프로그램을 업데이 트에 대한 시간이 없어, 난 WP8보기에 대해 아무것도 몰랐 24 시간있다 ... – Vadorequest

관련 문제