Reputation: 533
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 ?
Upvotes: 1
Views: 1652
Reputation: 128106
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>
Upvotes: 3