2011-03-17 77 views
2

我有一个WCF调用,返回一个对象列表。WP7绑定列表框到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方法的底部,然后我看到1个项目出现在listbx的UI

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

这证明绑定是正确的,但似乎是因为延迟在Asynch WCF调用中,UI不会更新。

仅供参考我已经更新MainPage.xaml中列表框绑定到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> 

什么我做错了任何想法呢?

感谢

回答

4

当您的ListBox首次创建时,其ItemsSource属性取当前值Itemsnull。当您的WCF呼叫完成并为Items分配一个新值时,如Greg Zimmers在他的答案中所提到的,视图无法知道该属性的值已经发生变化,而您没有发起PropertyChanged事件。

由于您使用的是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; 
} 
1

请问您的数据实体“站在”实现INotifyPropertyChanged接口和你提升属性更改事件?

+0

它是在引用WCF服务时生成的标准CLR对象。看着它,它确实实现了INotifyProperty接口,它确实引发了属性更改的事件 – Gavin 2011-03-17 21:05:09

+0

@Gavin Draper:它不是WCF服务,而是'Items'所属的需要实现'INotifyProperty'的类。 – Praetorian 2011-03-17 21:25:46

+0

Item引用的基类是Visual Studio在将WCF服务指向一个返回组合类型的WCF服务时生成的CLR对象。该对象支持INotifyPropertyChanged – Gavin 2011-03-18 06:04:52