I want to create dynamic comboboxes based on a list of datatables. Every time I add a new datatable to the list I want the UI to generate a new combobox which displays the column I specify from the table. I tried it with a itemscontrol and datatemplate but doesn't work like I want.
public List<DataTable> DtList
{
get { return dtList; }
set { dtList = value; }
}
<ItemsControl ItemsSource="{Binding Path=DtList}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate >
<DataTemplate>
<ComboBox
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left"
Margin="0,0,4,10"
Width="200"
BorderBrush="{DynamicResource ListBox.Static.Border}"
ItemsSource="{Binding DataSet}"
DisplayMemberPath="Element Name"
SelectedValuePath="ResourceType Name"
SelectedValue="{Binding SelectedRelationPath, Mode=TwoWay}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I've just created a sample and it's working for me
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
// this.DataContext = this; Uncomment this if code behind is your datacontext
InitializeComponent();
DataTable t1 = new DataTable();
t1.Columns.Add("Name");
t1.Columns.Add("Age");
t1.Rows.Add("A", "1");
t1.Rows.Add("B", "2");
DataTable t2 = new DataTable();
t2.Columns.Add("Name");
t2.Columns.Add("Age");
t2.Rows.Add("A", "1");
DtList = new List<DataTable> { t1, t2 };
}
private List<DataTable> dtList;
public List<DataTable> DtList
{
get { return dtList; }
set
{
dtList = value;
OnPropertyChanged("DtList");
}
}
private string selectedName;
public string SelectedName
{
get { return selectedName; }
set
{
selectedName = value;
OnPropertyChanged("SelectedName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler == null) return;
handler(this, new PropertyChangedEventArgs(name));
}
}
In your Xaml add this in your window or UserControl tag
x:Name="windowName"
Now do this
<StackPanel>
<ItemsControl ItemsSource="{Binding Path=DtList}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate >
<DataTemplate>
<ComboBox
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left"
Margin="0,0,4,10"
Width="200"
ItemsSource="{Binding}"
DisplayMemberPath="Name"
SelectedValuePath="Age"
SelectedValue="{Binding Path=SelectedName,ElementName=windowName}"
/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
This works fine for me.