views:

45

answers:

2

I have two classes

Company
    CompanyKey
    CompanyName

Person
    FirstName
    LastName
    CompanyKey

The list items on the combo box is bound to a collection of CompanyObjects.

How to I databind the selected item property of the Combobox to the Person.CompanyKey property?

A: 

The solution is simple, you need to use an IValueConverter to convert to Company to the Person object.

For more information on IValueConverter, please see: http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

You can then bind it in your xaml with something like: {Binding Path=combox.SelectedItem, Converter={StaticResource CompanyToPersonConvertor}}

MuSTaNG
+1  A: 

If I've understood your question correctly, here is a demo app that explains databinding of combo box: Demo App

Hope this helps.
Regards,
Mihir Gokani

EDIT: Fragment from code sample

<Window
    x:Class="WpfApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1"
    Height="300"
    Width="300">
    <StackPanel>

        <TextBlock
            Margin="10">Persons</TextBlock>
        <ComboBox
            x:Name="comboPersons"
            Height="25"
            Margin="10"
            ItemsSource="{Binding Persons}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel
                        Orientation="Horizontal">
                        <TextBlock
                            Text="{Binding FirstName}"
                            Margin="0,0,5,0" />
                        <TextBlock
                            Text="{Binding LastName}" />
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

        <TextBlock
            Margin="10">Companies</TextBlock>
        <ComboBox
            x:Name="comboCompanies"
            Height="25"
            Margin="10"
            ItemsSource="{Binding Companies}"
            DisplayMemberPath="CompanyName"
            SelectedValuePath="CompanyKey"
            SelectedValue="{Binding SelectedItem.CompanyKey, ElementName=comboPersons}" />

    </StackPanel>
</Window>
Mihir Gokani
That looks too easy. I was expecting it to be a big pain in the ass, not just a couple of properties.
Jonathan Allen