简体   繁体   中英

Data binding to a UserControl

I have a viewModel which is used to bind to a user control. The user control is basically a AdRotator. One of the feature of AdRotator is that it can be used in multiple positions on same screen. Seperate set of ads will be displayed on these multiple adRotators. The single view model exposes 4 observable collections which is deputed for adRotators on various locations . My problem is that since user controls are 'drag n drop' use i am a looking for a identification method that will let me determine which observablecollection(of the 4) should the an adRotator bind to. Please let me know what are the approaches for this.

Will it be a good approach if i retrieve the name of the user control and bind the collection depending on the name?

I don't know the specifics of your view models so I will offer one possible approach expressed in general terms.

Suppose you have a view model with four child view models which are all variations that have properties that the bindings in your user control are looking for and are named Vm1, Vm2, etc. which in your case could be your ad collections. You could bind the DataContext of each instance of you user control to each of the child view models.

    <my:SampleUserControl DataContext="{Binding Path=Vm1}" />
    <my:SampleUserControl DataContext="{Binding Path=Vm2}" />
    <my:SampleUserControl DataContext="{Binding Path=Vm3}" />
    <my:SampleUserControl DataContext="{Binding Path=Vm4}" />

This way each instance of your user control can bind to and display different data.

ViewModels are for logical parts of your application. For reusable controls, I would create a regular UserControl with code behind. This Control can expose API through properties and events, and in your case would expose a Dependency Property that would get the list of "ads".

This way you can position them all in a View, where each AdRotator control is bound to a different collection. This way the logic would sit in only one place - the ViewModel, and the reusable UI would sit in a dedicated control.

View+ViewModels are for logical seperation (Single Responsibility Principle, SRP) where are reusable controls are for reuse (or DRY: don't repeat yourself). It's very important to identify which type of control you are using. regular reusable controls should not contain ViewModel.

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