簡體   English   中英

WP7將列表框綁定到WCF結果

[英]WP7 Binding Listbox to WCF result

我有一個WCF調用,它返回對象列表。

我已經創建了WP7 Silverlight Pivot應用程序,並修改了MainViewModel以從WCF服務加載數據,LoadData方法現在看起來像這樣

public ObservableCollection<Standing> Items { get; private set; }

public void LoadData()
{
    var c = new WS.WSClient();
    c.GetStandingsCompleted += GetStandingsCompleted;
    c.GetStandingsAsync();            
}

void GetStandingsCompleted(object sender, GetStandingsCompletedEventArgs e)
{
    Items = e.Result;
    this.IsDataLoaded = true;
}

這會運行,如果我在完成的事件上設置一個斷點,我可以看到它成功運行,並且我的Items集合現在有50個奇數項目。 但是,UI中的列表框不會顯示這些。

如果將以下行添加到我的LoadData方法的底部,那么我會在UI的listbx中看到1個項目

Items.Add(new Standing(){Team="Test"});

這證明了綁定是正確的,但是由於Asynch WCF調用的延遲,UI並未更新。

作為參考,我更新了MainPage.xaml列表框以綁定到我的Standing對象上的Team屬性。

<ListBox x:Name="FirstListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
          <StackPanel Margin="0,0,0,17" Width="432">
                <TextBlock Text="{Binding Team}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                <TextBlock Text="{Binding Team}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
          </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

關於我在做什么錯的任何想法嗎?

謝謝

首次創建ListBoxItemsSource屬性采用Items的當前值,該值為null 當您完成WCF調用並將新值分配給Items ,如您無法觸發PropertyChanged事件,視圖就無法知道該屬性的值已更改,正如Greg Zimmers在回答中提到的那樣。

由於您使用的是ObservableCollection ,因此另一種方法是首先創建一個空集合,然后在WCF調用完成時向其添加對象。

private ObservableCollection<Standing> _items = new ObservableCollection<Standing>();
public ObservableCollection<Standing> Items
{ 
  get { return _items; } 
  private set;
}


void GetStandingsCompleted(object sender, GetStandingsCompletedEventArgs e)
{
    foreach( var item in e.Result ) Items.Add( item );
    this.IsDataLoaded = true;
}

您的數據實體“站立”是否實現INotifyPropertyChanged接口,並且是否引發屬性更改事件?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM