Is it possible to Bind the DataContext of a UserControl to a property

前提是你 提交于 2019-12-11 06:23:46

问题


I have a user control that I would like to use in two different contexts. The user control needs its DataContext set to an instance of an appropriate ViewModel that has been created by the parent view/viewmodel.

I was hoping for something like:

<local:Child DataContext="{Binding ChildViewModel}"/>

where ChildViewModel is a inpc-styled property of the ViewModel that the page is bound to.

That doesn't seem to work. Is it possible to assign the DataContext by using Binding?


回答1:


It would probably be simpler to bind the Content of an ContentControl to your child ViewModel like this:

<ContentControl Content="{Binding ChildViewModel}" />

..and then have a DataTemplate to apply your local:Child View, like this

<DataTemplate DataType="{x:Type local:ChildViewModel}">
    <local:Child />
</DataTemplate>


来源:https://stackoverflow.com/questions/4994595/is-it-possible-to-bind-the-datacontext-of-a-usercontrol-to-a-property

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