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

前端 未结 1 1970
借酒劲吻你
借酒劲吻你 2021-01-17 04:16

My colleague and I have been desperately trying to understand why we can\'t get a collection of ViewModels to render as expected. We have created a very simple example that

相关标签:
1条回答
  • 2021-01-17 05:16

    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.

    0 讨论(0)
提交回复
热议问题