1

I have a observable collection in my view model like in the following.

           private ObservableCollection<MyClass> _myData;
           public  ObservableCollection<MyClass> MyData
           {
                  set { _myData=value; }
                  get { return _myData }
           }

The structure of MyClas is like in the following.

          class MyClass 
          {
                 private string name;
                 public string Name;
                 {
                     set { name=value;}
                     get { return name;}
                 }
           }

I have binded the above observable collection to a combobox in my view like this.

       <ComboBox  Width="200" 
              ItemsSource="{Binding DataContext.MyData.Name,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/>

Still it says

BindingExpression path error: 'Name' property not found on 'object' ''ObservableCollection`1' (HashCode=22227061)'. BindingExpression:Path=DataContext.MyData.Name; DataItem='MyView' (Name=''); target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')

I find this strange. why does it say that Name property is not there in observable collection ?

1
  • Change the property Name to something else, like DName and try... Commented May 9, 2015 at 5:34

1 Answer 1

3

You get that error message because the property path DataContext.MyData.Name resolves a Name property in MyData, which isn't there and doesn't make sense.

You should bind the ItemsSource property to the item collection, and set the DisplayMemberPath to the Name property of the item class:

<ComboBox ItemsSource="{Binding DataContext.MyData,
                        RelativeSource={RelativeSource FindAncestor,
                                        AncestorType=UserControl}}"
          DisplayMemberPath="Name"/>

Alternatively you could create a DataTemplate that binds to the Name property:

<ComboBox ItemsSource="{Binding DataContext.MyData,
                        RelativeSource={RelativeSource FindAncestor,
                                        AncestorType=UserControl}}"/>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.