CollectionViewSource bind source to webservice (using WCF RIA services and LINQ) - Silverlight

亡梦爱人 提交于 2019-12-24 11:13:04

问题


I have a small problem, probably stupid but I can't figure this out.. Anyways all I'm trying to do is bind my CollectionViewSource.Source to my resulting query in Silverlight 4 with WCF RIA services.

This is my XAML :

<UserControl.Resources>
    <CollectionViewSource x:Name="cvsServiceTypes" />
</UserControl.Resources>
<Grid>
    <ComboBox Height="23" HorizontalAlignment="Left" ItemsSource="cvsServiceTypes" DisplayMemberPath="Type" SelectedValuePath="IDServicesType" Margin="154,51,0,0" Name="cbServiceType" VerticalAlignment="Top" Width="120" SelectedValue="{Binding fkservicetype, Mode=TwoWay}" />
</Grid>

And my CodeBehind :

  public Services()
  {
      InitializeComponent();

      webService.GetServiceTypesCompleted += (s, e) => { cvsServiceTypes.Source = e.Result; };
      webService.GetServiceTypesAsync();
   }

But it doesn't seem to work... what am I doing wrong?

Thank you very much!


回答1:


I hope you don't mind if I ignore the web service call part - it looks like you're struggling with binding your items to the ComboBox, so that's the part I'll address.

You need to do the following:

  1. Create an ObservableCollection property to contain your items.
  2. Bind the CollectionViewSource.Source to the ObservableCollection.
  3. Bind the ComboBox.ItemsSource to the CollectionViewSource.
  4. Set the DataContext on your UserControl.

Here is an example:

<UserControl ...>
    <StackPanel>
        <StackPanel.Resources>
            <CollectionViewSource x:Key="cvs" Source="{Binding Path=Items}"></CollectionViewSource>
        </StackPanel.Resources>
        <ComboBox ItemsSource="{Binding Source={StaticResource ResourceKey=cvs}}" />
        <ComboBox ItemsSource="{Binding Source={StaticResource ResourceKey=cvs}}" />
        <ComboBox ItemsSource="{Binding Source={StaticResource ResourceKey=cvs}}" />
    </StackPanel>
</UserControl>

The code:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
        this.DataContext = this;
        _items.Add("a");
        _items.Add("b");
    }

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

You can put items into the collection when your web service call completes like this:

webService.GetServiceTypesCompleted += (s, e) => 
{
    foreach (string s in e.result)
    {
        _items.Add(s);
    }
};


来源:https://stackoverflow.com/questions/5589017/collectionviewsource-bind-source-to-webservice-using-wcf-ria-services-and-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!