开发者

WP7 Binding Listbox to WCF result

I have a WCF call that returns a list of objects.

I've created a WP7 Silverlight Pivot application and modified the MainViewModel to load data from my WCF service, the LoadData method now looks like this

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

public void LoadData()
{
    var c = 开发者_如何学Gonew WS.WSClient();
    c.GetStandingsCompleted += GetStandingsCompleted;
    c.GetStandingsAsync();            
}

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

This runs and if I put a break point on the completed event I can see it ran successfully and my Items collection now has 50 odd items. However the listbox in the UI doesnt display these.

If I add the following line to the bottom of my LoadData method then I see 1 item appear in the listbx on the UI

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

This proves the bindings are correct but it seems that because of the delay in the Asynch WCF call the UI doesn't update.

For reference I've updates the MainPage.xaml listbox to bind to the Team property on my Standing object

<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>

Any ideas on what I'm doing wrong?

Thanks


When your ListBox is first created its ItemsSource property takes the current value of Items which is null. When your WCF call completes and you assign a new value to Items, the view has no way of knowing that the value of that property has changed without you firing a PropertyChanged event, as Greg Zimmers mentions in his answer.

Since you're using an ObservableCollection, an alternative method would be to initially create an empty collection and then add objects to it when the WCF call completes.

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;
}


Does your data entity "Standing" implement the INotifyPropertyChanged interface and do you raise the property changed event?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜