简体   繁体   中英

Databinding within ComboBox: Use Usercontrol to display each item

I have a model-class Person and a UserControl PersonComboBoxItem to display it.

What I'd like to do, is, creating a ComboBox where its ItemsSource is bound to my ObservableCollection<Person> called People and use my PersonUserControl to display each Person within the collection.

<Grid>
    <ComboBox SelectedIndex="0" ItemsSource="{Binding People}" >            
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <local:PersonComboBoxItem Person="{Binding ###how do I get the current item here to set the property 'Person' on my PersonComboBoxItem class? ###  }"  />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</Grid>

I already worked my way thorugh this great article about databinding on msdn , but I couldn't get the transition over to my design-approach. Feel free to critisize it - I'm not sure, if this is the WPF-way to do it.

Regards, Florian

PS: My sample code can be downloaded from here .

Simply use an implicit DataTemplate to tell WPF how to draw the Person object when it encounters it in the visual tree

<Grid>
    <ComboBox SelectedIndex="0" ItemsSource="{Binding People}" DisplayMemberPath="Name">            
        <ComboBox.Resources>
            <DataTemplate DataType="{x:Type local:Person}">
                <local:PersonComboBoxItem />
            </DataTemplate>
        </ComboBox.Resources>
    </ComboBox>
</Grid>

The ComboBox is already placing your Person data object in the VisualTree , and probably looks something like this:

<StackPanel>
    <ContentPresenter>
        <Person />
    </ContentPresenter>
    <ContentPresenter>
        <Person />
    </ContentPresenter>
    <ContentPresenter>
        <Person />
    </ContentPresenter>
    ...
</StackPanel>

So you are simply replacing where it says <Person /> with a <local:PersonComboBoxItem /> . The DataContext of your UserControl will be set to your Person object as well

Also, the DataContext of the PersonItemComboBox will always be of type Person , so you won't even need the Person dependency property.

The DataContext in the ItemTemplate is the current Person , to bind directly to the DataContext and thus to the Person just use {Binding} .

You could design your UserControl to directly use the current DataContext instead of a Person property, then you do not need to set anything explicitly.

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