Here is a very simple example. Note that I have a StackPanel (horizontal) to which I am going to add the comboboxes as I create them.
<window x:class="WpfSample.MainWindow" xmlns:x="#unknown">
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AddControls" Height="314" Width="664" Loaded="Window_Loaded">
<stackpanel name="SpnlMain" margin="5">
<datagrid horizontalalignment="Left" height="189" margin="10,0,0,0" width="442" x:name="PresidentsGrid" />
<stackpanel name="CombosPnl" height="10" orientation="Horizontal" margin="5" />
</stackpanel>
</window>
And the code
using System.Windows;
using System.Windows.Controls;
namespace WpfSample
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
PresidentsGrid.ItemsSource = President.GetPresidents();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var p = new President().GetType().GetProperties();
for (var i = 0; i < PresidentsGrid.Columns.Count; i++)
{
var newCombo = new ComboBox
{
Name = string.Format("Combo{0}", i),
Width = 120,
ItemsSource = President.GetPresidents(),
DisplayMemberPath = p[i].Name,
SelectedValuePath = p[i].Name
};
CombosPnl.Children.Add(newCombo);
}
}
}
}
This populates a datagrid with a list of US Presidents and then dynamically adds a comboBox for each column in the grid. Each comboBox contains all of the values for the equivalent column. If a new property is added to the class there are no changes to this code required .
Warning - I used reflection to get the properties of my data class into an array so I could easily assign the DisplayMemberPath and SelectedValuePath properties using the loop counter. This only works if the GetPresidents method returns ALL of the class' properties in the order they are defined.
For completeness here is my President class:
using System.Collections.ObjectModel;
namespace WpfSample
{
class President
{
public string FirstName { get; set; }
public string Surname { get; set; }
public int Start { get; set; }
public int Until { get; set; }
public int Number { get; set; }
public President(string fn, string sn, int s, int u, int n)
{
FirstName = fn;
Surname = sn;
Start = s;
Until = u;
Number = n;
}
public President() { }
public static ObservableCollection<president> GetPresidents()
{
var sams = new ObservableCollection<president>
{
new President("George", "Washington", 1789, 1797,1),
new President("John", "Adams", 1797, 1801,2),
new President("Thomas", "Jefferson", 1801, 1809,3),
new President("James", "Madison", 1809, 1817,4),
new President("James", "Monroe", 1817, 1825,5),
new President("John Quincy", "Adams", 1825, 1829,6),
new President("Andrew", "Jackson", 1829, 1837,7),
new President("Martin", "Van Buren", 1837, 1841,8),
new President("William Henry", "Harrison", 1841,1841,9),
new President("John", "Tyler", 1841, 1845,10)
};
return sams;
}
}
}</president></president>