user627283
user627283

Reputation: 553

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

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!

Upvotes: 1

Views: 1139

Answers (1)

Greg Sansom
Greg Sansom

Reputation: 20860

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

Upvotes: 2

Related Questions