WPF - How to get SelectedIndex of a ComboBox defined in a DataTemplate?
In my WPF app I have a data import function which imports data from an Excel file into a database.
In order to allow user to map the columns from their Excel file to the columns in my database table I am displaying the list of Excel columns in a ComboBox
next to database table column names allowing the user to select the matching Excel column from the ComboBox
.
This is displayed in a ListBox
with each item containing a ComboBox
and a TextBlock
.
The ListBox
is Data Bound to a Dictionary<ColumnsClass, List<string>>
where ColumnsClass
is a simple object containing database column names and other details and the List<string>
is just a list of column names found in the Excel file. In order to display the List<string>
in the ComboBox
I have a DataTemplate defined as such:
<DataTemplate x:Key="ColumnList">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" ItemsSource="{Binding Value, Mode=OneWay}">
</Combo开发者_C百科Box>
<TextBlock Grid.Column="1" Text="{Binding Key, Mode=OneWay}"/>
</Grid>
</DataTemplate>
Once the user maps the Excel columns to database column names and starts the import I need to be able to get the database column name and the matching 'ComboBox' 'SelectedIndex' value of each item in the ListBox
but the each item in the ItemsSource is actually a KeyValuePair<ColumnsClass, List<string>>
so I don't see how to get the 'ComboBox' 'SelectedIndex' value while iterating through the ListBox.Items
collection...
Any ideas?
If you use the Dictionary
just as a IEnumerable<KeyValuePair<ColumnsClass, List<string>>>
, you could create a custom class to hold the two values and add a value specifying user's choice:
class ViewModel
{
public ColumnClass ColumnClass { get; set; }
public List<string> ColumnNames { get; set; }
public string SelectedColumn { get; set; }
}
Then use List<ViewModel>
(or any other collection) instead of your Dictionary
and bind to SelectedColumn
in your XAML:
<DataTemplate x:Key="ColumnList">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" ItemsSource="{Binding ColumnNames, Mode=OneWay}"
SelectedItem="{Binding SelectedColumn}" />
<TextBlock Grid.Column="1" Text="{Binding ColumnClass, Mode=OneWay}"/>
</Grid>
</DataTemplate>
If, for some reason, you didn't want to create a separate class and you're on .Net 4, you could use Tuple<ColumnClass, List<string>, string>
instead of ViewModel
.
精彩评论