ComboBox to link one entity to another.

I don’t forget WPF! Here is a pretty common situation in which you may need to link (via UI) two entities.

For example, you have a list of people and a list of programming languages.

In a view need to assign to each person their favorite programming language.

  • José Manuel => C#
  • Luis Javier => Java

Something like this:

Linking

This is the code I had to write!🙂 (The XAML is the important thing here).

<Window x:Class="Lenguage.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:lenguage="clr-namespace:Lenguage"
        xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <collections:ArrayList x:Key="People">
            <lenguage:Person Name="José Manuel"></lenguage:Person>
            <lenguage:Person Name="Luis Javier"></lenguage:Person>
        </collections:ArrayList>
        <collections:ArrayList x:Key="ProgrammingLanguages">
            <lenguage:ProgrammingLanguage Name="C#"></lenguage:ProgrammingLanguage>
            <lenguage:ProgrammingLanguage Name="Java"></lenguage:ProgrammingLanguage>
        </collections:ArrayList>
    </Window.Resources>
    <Grid>
        <DataGrid ItemsSource="{StaticResource People}" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Person" Width="*" Binding="{Binding Name}" />
                <DataGridTemplateColumn Header="Favorite language" Width="*">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate DataType="{x:Type lenguage:Person}">
                            <ComboBox DisplayMemberPath="Name"                                
                                      ItemsSource="{StaticResource ProgrammingLanguages}"
                                      SelectedItem="{Binding FavoriteLanguage, UpdateSourceTrigger=PropertyChanged}"
                                      IsSynchronizedWithCurrentItem="False"                                      
                                      />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s