WP7将列表框绑定到WCF结果
我有一个WCF调用,它返回一个对象列表 我已经创建了一个WP7 Silverlight Pivot应用程序,并修改了MainViewModel以从我的WCF服务加载数据,LoadData方法现在如下所示WP7将列表框绑定到WCF结果,wcf,data-binding,windows-phone-7,Wcf,Data Binding,Windows Phone 7,我有一个WCF调用,它返回一个对象列表 我已经创建了一个WP7 Silverlight Pivot应用程序,并修改了MainViewModel以从我的WCF服务加载数据,LoadData方法现在如下所示 public ObservableCollection<Standing> Items { get; private set; } public void LoadData() { var c = new WS.WSClient(); c.GetStandingsC
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;
}
这证明了绑定是正确的,但似乎由于异步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>
你知道我做错了什么吗
谢谢您的数据实体是否实现了INotifyPropertyChanged接口,是否引发了属性更改事件?首次创建ListBox时,其ItemsSource属性采用当前为null的项值。当您的WCF调用完成并且您为项分配了一个新值时,视图无法在您不触发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;
}
它是在引用WCF服务时生成的标准CLR对象。看看它,,它确实实现了INotifyProperty接口,并且确实引发了已更改的属性event@GavinDraper:需要实现INotifyProperty的不是WCF服务,而是Items所属的类。Items引用的基类是一个CLR对象,当您将其指向返回复合属性的WCF服务时,visual studio会生成该对象类型此对象支持INotifyPropertyChanged
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;
}