Binding UserControl inside a ListView datatemplate WPF

蹲街弑〆低调 提交于 2019-12-06 14:12:47

Like I mentioned in the comment issue is in your UserControl, you have explicitly set DataContext of userControl to itself:

Me.DataContext = Me

So, binding label="{Binding detail}" looking for property detail in dataContext of UserControl (itself) and not in underlying dataContext of ListBoxItem.

You have to do explicit binding in case you want to look for item in DataContext of ListBoxItem like:

label="{Binding DataContext.detail,
                RelativeSource={RelativeSource Mode=FindAncestor, 
                                            AncestorType=ListBoxItem}}"

OR

You should remove setting DataContext to itself in UserControl.

You must have set it to bind with declared DP's. I would suggest to bind that using ElementName and remove setting DataContext. That way you don't have to give explicit binding and your UserControl will automatically inherit DataContext from its Visual parent.

<UserControl x:Name="myUserControl">
   <Label Content="{Binding label, ElementName=myUserControl}"/>
   <TextBlock Text="{Binding text, ElementName=myUserControl}"/>
</UserControl>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!