DataContext in UserControls

梦想与她 提交于 2019-12-13 02:26:23

问题


How are DataContext in UserControls usually set? If I do something like the below in my UserControl,

DataContext = this

In my Window or other Controls when I want to use the Control with a Binding, I will have to have a RelativeSource to point to the Window/UserControl

<local:UserControl1 TextContent="{Binding Text1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

Is the way to bind Controls within UserControls: set use RelativeSource in UserControls instead of DataContext?

<UserControl x:Class="SetCurrentValueTest.UserControl1" ...>
    <TextBox Text="{Binding Path=TextContent, RelativeSource={RelativeSource AncestorType={x:Type local:UserControl1}}}" />
</UserControl>

回答1:


I dunno if it is what you are looking for, but if you want to bind to the UserControls Dependency-Properties, use this:

<UserControl x:Class="SetCurrentValueTest.UserControl1" ...>
    <TextBox Text="{Binding Path=TextContent, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</UserControl>

And if you want to bind to the UserControl's DataContext, use this Binding:

<UserControl x:Class="SetCurrentValueTest.UserControl1" ...>
    <TextBox Text="{Binding Path=DataContext.TextContent, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</UserControl>

Not that I am specifying UserControl as Ancestor-Type and not your Concrete Type (UserControl1).



来源:https://stackoverflow.com/questions/4237443/datacontext-in-usercontrols

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