How to access parent's DataContext from a UserControl

后端 未结 4 2083
旧时难觅i
旧时难觅i 2020-12-10 14:25

I need to access the container\'s DataContext from a UserControl (a grid containing textboxes and a listbox: I need to insert items in this list box) that I created in WPF:

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 14:53

    H.B. answers the question in your title.

    However the text poses a different design question. I'd ask you to reconsider your design.

    A control inherits the DataContext property of its ancestor as long as no one in between explicitly overrides.
    If the user control needs data, it should get it from its data source (a viewmodel for the user control). So in this case, the user control can obtain the data it needs from the ListItemsForDisplay property exposed on the SomeViewModel instance. No need to get parent and cast.. much cleaner.

    
      
        
    ...
    

提交回复
热议问题