【问题标题】:WP7 Binding Listbox to WCF resultWP7 绑定列表框到 WCF 结果
【发布时间】:2011-03-17 20:18:44
【问题描述】:

我有一个返回对象列表的 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"});

这证明绑定是正确的,但似乎由于异步 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>

关于我做错了什么有什么想法吗?

谢谢

【问题讨论】:

    标签: wcf data-binding windows-phone-7


    【解决方案1】:

    当您的ListBox 首次创建时,其ItemsSource 属性采用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;
    }
    

    【讨论】:

      【解决方案2】:

      您的数据实体“Standing”是否实现了 INotifyPropertyChanged 接口,您是否引发了属性更改事件?

      【讨论】:

      • 它是在您引用 WCF 服务时生成的标准 CLR 对象。看着它,它确实实现了 INotifyProperty 接口,并且确实引发了属性更改事件
      • @Gavin Draper:不是WCF服务而是Items所属的类需要实现INotifyProperty
      • Items 引用的基类是一个 CLR 对象,当您将其指向返回复合类型的 WCF 服务时,Visual Studio 会生成该对象。此对象支持 INotifyPropertyChanged
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多