How to setup UserControl

血红的双手。 提交于 2019-12-25 19:04:15

问题


In an application I have the (simplified) task:

The application manages information about persons. The persons are stored somewhere (doesn't matter). The user can add and remove persons to the list.

The list of persons (that is used quite often in the program) looks like this:

<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>

Behind that works a ViewModel that I want to use for implementation.

Now I want wo have this control embedded into another Control/Window like this:

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

(PersonsVM and SelectedPersonVM are Properties in the VM of the UC/Window that embeds the PersonControl-UC, PersonsDP and SelectedPersonDP are DependencyProperty of the PersonControl-UC.)

I have the problem having the properties of the UC as a DependencyProperty and (at the same time) having as Properties in the UC-ViewModel.

How can I accomplish that?


UPDATE 1

Found this link where exactly my problem is discussed but still not answered. Maybe someone has a new idea...


回答1:


It is all about datacontext. You could keep the bindings in usercontrol definition and later in parts where you embed your UC bind datacontext to a corresponding VM which provides your datasource of persons.

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

And in VM you would 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;}
}



回答2:


EDIT:

usually you use elementname binding when working with usercontrol and DP.(never set the DataContext to self)

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

then your usercontrol stuff 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>


来源:https://stackoverflow.com/questions/22249388/how-to-setup-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!