2013-01-04 4 views
2

이것은 내 C# 코드입니다. 이제 콘솔에 데이터가 표시됩니다.Xaml, Windows Phone에 데이터를 바인딩하는 방법은 무엇입니까?

class PlaceViewModel 
    { 

     public List<Vantaa.IntroPage.Place> Places; 
    }  

public class Place 
      { 
       public string id { get; set; } 
       public string title { get; set; } 
       public string latitude { get; set; } 
       public string longitude { get; set; } 
       public string www { get; set; } 
      } 

     public class RootObject 
     { 
      public List<Place> Places { get; set; } 
     } 

    protected override void OnNavigatedTo(NavigationEventArgs e) 
     { 
      WebClient webClient = new WebClient(); 
      webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted); 
      webClient.DownloadStringAsync(new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place")); 
     } 

     private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result); 

      foreach (var book in rootObject.Places) 
      { 
       System.Diagnostics.Debug.WriteLine(book.id); 
      } 
      this.DataContext = new PlaceViewModel 
       { 
         Places = rootObject.Places 
       }; 
      } 

데이터를 텍스트 블록으로 표시하려면 어떻게해야합니까?

이것은 현재 xaml 코드입니다. 확실히 작동하지 않습니다. 나는 정말로 모른다.

<ListBox ItemsSource="{Binding Places}"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <Grid> 
         <TextBlock Text="{Binding Path=id}" /> 
        </Grid> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

답변

5

클래스 코드가 좋으므로 결과를보기에 바인딩해야합니다. 개체 목록을 반환하면 여러 항목 표시를 지원하는 컨트롤을 사용해야합니다. 물론 책의 모든 ID를 하나의 문자열로 연결하여 레이블에 표시 할 수 있습니다. 그러나 이것이 어떻게 완료되었는지는 아닙니다. ListBox 컨트롤을 XAML에 추가하고 그 안에 DataTemplate을 만듭니다. 이렇게하면 항목이 표시되는 방식을 설정할 수 있습니다.

XAML 페이지의 ViewModel이 될 클래스를 만듭니다. 이 수업에는 '장소'속성 (유형 : List<Place>)이 있습니다. 모든 데이터가 완료 점점 때 OnNavigatedTo 이벤트에서 뷰 모델을 작성하고 결합하고 XAML의 DataContext에에 바인딩 :

this.DataContext = new YourViewModel { Places = rootObject.Places }; 

당신이 당신의 XAML에서 뷰 모델에서 모든 개체를 잡아 수있는이 방법 :

<ListBox ItemsSource="{Binding Places}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <TextBlock Text="{Binding Path=id}" /> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

편집 :

다음은

가 작동 예제 0

XAML :

<Grid> 
    <ListBox ItemsSource="{Binding Places}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding Path=ID}" /> 
        <TextBlock Text="{Binding Path=Title}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 

Place.cs :

public class Place 
{ 
    public string ID { get; set; } 
    public string Title { get; set; } 
    public string Latitude { get; set; } 
    public string Longitude { get; set; } 
    public string Web { get; set; } 
} 

MainViewModel.cs :

public class MainViewModel 
{ 
    public MainViewModel() 
    { 
     Places = new List<Place>(); 
    } 

    public List<Place> Places { get; set; } 
} 

샘플 저장소 (자신이 있어야합니다)

public static List<Place> FetchData() 
{ 
    var lst = new List<Place>(); 

    lst.Add(new Place { ID = "1", Title = "One", Latitude = "111", Longitude = "111", Web = "www......" }); 
    lst.Add(new Place { ID = "2", Title = "Two", Latitude = "222", Longitude = "222", Web = "www......" }); 
    lst.Add(new Place { ID = "3", Title = "Three", Latitude = "333", Longitude = "333", Web = "www......" }); 
    lst.Add(new Place { ID = "4", Title = "Four", Latitude = "444", Longitude = "444", Web = "www......" }); 

    return lst; 
} 

MainWindow.xaml.cs를 :

public MainWindow() 
{ 
    InitializeComponent(); 
    //This is where the magic happens 
    //Fill the viewModel with the data 
    var viewModel = new MainViewModel { Places = Repository.FetchData() }; 
    //Assign the viewModel with the data to the DataContext 
    //The bindings will be automatically done in the XAML 
    DataContext = viewModel; 
} 
+0

당신에게 대단히 감사합니다! –

+0

작동하지 않습니다. 코드를 편집했습니다. 어떠한 제안? –

+0

당신은 ViewModel 클래스를 만들까요? 가져온 데이터로 속성을 채웠습니까?당신은 ViewModel을 DataContext에 할당합니까? – Abbas

2

귀하의 PlaceViewModel 클래스는 INotifyProprtyChanged 인터페이스 및 세터에서 변경 사항을 알려야합니다 바인딩 할 모든 속성을 구현해야합니다.

바운드 텍스트 블록에서 값을 업데이트하려면 속성이 변경 내용을 알릴 수 있습니다.

예 : http://msdn.microsoft.com/en-us/library/ms229614.aspx

+0

+1 팁 INotifyPropertyChanged 구현,하지만이 경우에는 기본 바인딩을 할 것입니다 생각합니다. 그러나 더 높은 수준의 바인딩으로 나아갈 때 당신은 절대적으로 옳습니다! :) – Abbas

관련 문제