Search code examples
c#silverlightmvvmwcf-ria-services

can't binding a simple combox with mvvm and wcf ria services


I have a simple project with domain service and I am trying to binding combox with domain service from my view model.

I am using mvvm design pattern, note that when I am not using mvvm design pattern and I am binding the combox from code behind I see the results on the combox.

enter code here


public class MainViewModel:INotifyPropertyChanged
{
    DomainService1 ctx = new DomainService1();
    private ObservableCollection<product> _products;
    public ObservableCollection<product> Products
    {

        get { return _products; }
        set {

            if (value != _products)
            {
                _products = value;
                OnPropertyChanged("Products");
            }
        }
    }

    public MainViewModel()
    {
        if (!DesignerProperties.IsInDesignTool)
        {
            LoadProdcuts();
        }
    }

    private void LoadProdcuts()
    {
        ctx.Load(ctx.GetProductsQuery(), LoadProdcutCallBack, null);
    }
    private void LoadProdcutCallBack(LoadOperation<product>lo)
    {
        _products = new ObservableCollection<product>(lo.Entities);
    }


    private void OnPropertyChanged(string propName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
enter code here

<UserControl.Resources>
    <data:MainViewModel x:Key="VwModel"/>
</UserControl.Resources>


    <ComboBox HorizontalAlignment="Left"  VerticalAlignment="Top" Height="30" Width="100" ItemsSource="{Binding Products}"/>

Solution

  • You must set DataContext property:

    <ComboBox HorizontalAlignment="Left"  VerticalAlignment="Top" Height="30" Width="100" 
                          DataContext="{StaticResource VwModel}"
                          ItemsSource="{Binding Products}"/>