0

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 !

4

1 回答 1

1

如果您的 ListOfString 看起来像这样:

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

那么您应该简单地删除 SelectedValuePath 和 DisplayMemberPath。因为否则 wpf 会查找字符串中不存在的属性 ListOfString :)

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

如果不是这种情况,您应该发布您的 ListOfString 属性的代码。

顺便说一句,您应该重命名 SelectedItem 属性或集合属性,因为 atm 都命名为 ListOfString。

于 2014-06-30T07:58:19.930 回答