简体   繁体   中英

MVVM Light pass ViewModel to ObjectDataProvider via ViewModelLocator

I have an ObjectDataProvider that binds to the GetProducts() method of my viewmodel:

<ObjectDataProvider x:Key="GetProducts"
                    ObjectType="vm:MainViewModel"
                    MethodName="GetProducts">
    <ObjectDataProvider.MethodParameters>
        <m:Subcategory Id="-1"/>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

As far as I understand this creates an instance of MainViewModel to call the method. Recently I started using MVVM Light and its ViewModelLocator class registers its own instance of the same viewmodel, so now I have two viewmodels instead of one.

That didn't feel right so I was wondering: is it possible to pass the viewmodel created by ViewModelLocator to the ObjectDataProvider ?

I tried using a binding but ObjectInstance property is apparently not a dependency property so it can't be used here. How else can I do that?

I managed to achieve this by getting rid of ObjectDataProvider entirely and adding some properties to my viewmodel instead, eg

    // This property took place of MethodParameter[0]
    public Subcategory SelectedSubcategory
    {
        get { return _selectedSubcategory; }
        set
        {
            Set(() => SelectedSubcategory, ref _selectedSubcategory, value);
            RaisePropertyChanged("Products");
        }
    }

    public IEnumerable<Product> Products
    {
        get
        {
            if (SelectedSubcategory != null)
                return SelectedSubcategory.Products;
            return null;
        }
    }

I also needed to change respective bindings in XAML, eg this:

SelectedItem="{Binding Source={StaticResource GetProducts},
                       Path=MethodParameters[0],
                       BindsDirectlyToSource=True,
                       UpdateSourceTrigger=PropertyChanged}"

turned into:

SelectedItem="{Binding SelectedSubcategory, Mode=OneWayToSource}"

Now I have only one viewmodel instance! Yay!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM