WPF binding to a collection of ViewModels fails to display as expected

馋奶兔 提交于 2019-12-01 14:15:52

A commonly made mistake in the implementation of a UserControl is to explicitly set its DataContext property to an instance of the expected view model, as you do by

<UserControl.DataContext>
    <local:StupidPersonViewModel />
</UserControl.DataContext>

Doing so effectively prevents that the UserControl inherits a DataContext from its parent control, as is expected in

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <local:StupidPersonView />
    </DataTemplate>
</ItemsControl.ItemTemplate>

where the inherited DataContext is an element of the ItemsSource collection.

Inheritance here means Dependency Property Value Inheritance.


So just don't explicitly set a UserControl's DataContext. Never. Any blogs or online tutorials telling you so are plain wrong.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!