WPF combobox dynamic binding

916 Views Asked by At

I've a combo box with in data grid edititemtemplate and i write some code in combo box loaded event like:

Code:

private void cmbGFld_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox cmb = (ComboBox)sender; 
            cmb.ItemsSource = FieldsList.GetFieldList();
            ConditionField cData = condLists[FieldGrid.SelectedIndex];
            cmb.SelectedItem = cData.FieldType;
        }

XAML Code:

<toolkit:DataGridTemplateColumn.CellEditingTemplate>
                                        <DataTemplate x:Name="editTemplate">
                                            <ComboBox Loaded="cmbGFld_Loaded" BorderBrush="Transparent" SelectedItem="{Binding Path=FieldType}" SelectedValuePath="Name" BorderThickness="0" FontSize="13" FontStyle="Italic" FontWeight="Normal" Foreground="DimGray" x:Name="cmbGFld" Template="{StaticResource ComboBoxTemplate2}">
                                                <ComboBox.Resources>
                                                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">Green</SolidColorBrush>
                                                </ComboBox.Resources>
                                                <ComboBox.ItemTemplate>
                                                    <DataTemplate>
                                                        <TextBlock HorizontalAlignment="Left"  Text="{Binding Name}"/>
                                        </DataTemplate>
                                                </ComboBox.ItemTemplate>
                                            </ComboBox>

                                        </DataTemplate>
                                    </toolkit:DataGridTemplateColumn.CellEditingTemplate>

But the problem is when ever i try to edit the combo box it doesn't showing which is already selected, any one help me.

Thanks, @nag.

1

There are 1 best solutions below

1
On

Try it without cmb.SelectedItem = cData.FieldType; in cmbGFld_Loaded(). This will overwrite the binding SelectedItem="{Binding Path=FieldType}" in your XAML. Set the selected item in the binded FieldType property instead. I don't know your application but something like:

FieldType = condLists[FieldGrid.SelectedIndex].FieldType;