How to configure UserControl

In the application, I have a (simplified) task:

The application manages face information. People are stored somewhere (it doesn't matter). The user can add and remove people to the list.

The list of persons (which are often used in the program) is as follows:

<UserControl> ... <StackPanel> <ListBox ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson}" SelectionMode="Single"/> <StackPanel Orientation="Horizontal"> <Button Content="Add Person" Command="{Binding AddPersonCommand}" /> <Button Content="Remove Person" Command="{Binding RemovePersonCommand}" /> </StackPanel> </StackPanel> ... </UserControl> 

The ViewModel that I want to use for implementation works behind this.

Now I want this control to be embedded in another control / Window:

 <personcontrol:PersonControl PersonsCollectionDP="{Binding PersonsFromMainVM}" SelectedPersonDP="{Binding SelectedPersonFromMainVM}" /> 

(PersonVM and SelectedPersonVM are properties in the UC / Window virtual machine that implement PersonControl-UC, PersonDP and SelectedPersonDP are DependencyProperty PersonControl-UC.)

I have a problem with UC properties like DependencyProperty and (at the same time) with properties in UC-ViewModel.

How can i do this?


UPDATE 1

Found this link where exactly my problem is being discussed, but still haven’t answered. Maybe someone has a new idea ...

-1
source share
2 answers

This is all about the datacontext. You can save the bindings in the usercontrol definition and later in the parts where you embed your datacontext UC bindings to the corresponding virtual machine, which provides your data source for individuals.

 <Window> <personcontrol:PersonControl DataContext="{Binding PersonsVM}" /> </Window> 

And in VM you will have

 public class WindowVM { public PersonsUCProviderVM PersonsVM {get;set;} } public class PersonsVM { public List<Person> Persons {get;set;} public Person SelectedPerson {get;set;} public ICommand AddPersonCommand {get;set;} public ICommand RemovePersonCommand {get;set;} } 
0
source

EDIT:

usually you use element name binding when working with usercontrol and DP (never set the DataContext yourself)

 <personcontrol:PersonControl PersonsCollectionDP="{Binding PersonsFromMainVM}" SelectedPersonDP="{Binding SelectedPersonFromMainVM}" /> 

then your usercontrol content should look like this:

 <UserControl x:Name="uc"> <StackPanel> <ListBox ItemsSource="{Binding ElementName=uc, Path=PersonsCollectionDP}" SelectedItem="{Binding ElementName=uc, Path=SelectedPersonDP}" SelectionMode="Single"/> </StackPanel> </UserControl> 
0
source

All Articles