1

我有一个带有域服务的简单项目,我正在尝试将组合框与我的视图模型中的域服务绑定。

我正在使用mvvm设计模式,请注意,当我不使用mvvm设计模式并且我从后面的代码中绑定组合框时,我会在组合框上看到结果。

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}"/>
4

1 回答 1

1

您必须设置DataContext属性:

<ComboBox HorizontalAlignment="Left"  VerticalAlignment="Top" Height="30" Width="100" 
                      DataContext="{StaticResource VwModel}"
                      ItemsSource="{Binding Products}"/>
于 2013-01-27T20:28:53.360 回答