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>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s