Binding a list of String to a DataGridTemplateColumn's ComboBox

980 views Asked by At

The question might seem quite easy but I can't get it and I tried everything I've found. It works for a list of class, since I can bind on one of my class' properties, but not for a simple ObservableCollection of String.

Here's my code in Xaml :

<DataGridTemplateColumn x:Name="VT" Header="VT" Width="*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox SelectedItem="{Binding ListOfString}"
                      SelectedValuePath="ListOfString"
                      DisplayMemberPath="ListOfString"
                      ItemsSource="{Binding RelativeSource={RelativeSource 
                                    Mode=FindAncestor,
                                    AncestorType={x:Type UserControl}},
                                    Path=DataContext.ListOfString}"/>
         </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

My code behind works fine since when I open the dropdown it displays as many rows as there are elements inside, but rows are empty. I also tried to work with the CellEditingTemplate thing like here but it has the same result in the best case. I think I'm getting wrong on those DisplayMemberPath properties and others, but I don't see what I should get inside.

So how can I correctly bind my ObservableCollection to my ComboBox ?

Thanks !

1

There are 1 answers

1
blindmeis On BEST ANSWER

if your ListOfString looks like this:

  public ObservableCollection<string> ListOfString {get;set;}

then you should simply remove the SelectedValuePath and DisplayMemberPath. because otherwise wpf looks for the Property ListOfString which does not exists on strings :)

        <ComboBox SelectedItem="{Binding ListOfString}"                     
                  ItemsSource="{Binding RelativeSource={RelativeSource 
                                Mode=FindAncestor,
                                AncestorType={x:Type UserControl}},
                                Path=DataContext.ListOfString}"/>

and if this is not the case you should post the code for your ListOfString property.

btw you should rename the SelectedItem property or the collection property, because atm both named ListOfString.