UserControls中的DataContext

时间:2010-11-21 10:46:07

标签: wpf user-controls binding datacontext

UserControls中的DataContext通常如何设置?如果我在UserControl中执行类似下面的操作,

DataContext = this

在我的窗口或其他控件中,当我想使用带有绑定的Control时,我必须有RelativeSource指向Window / UserControl

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

是否可以在UserControls中绑定控件:在UserControls中设置使用RelativeSource而不是DataContext

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

1 个答案:

答案 0 :(得分:1)

我不知道它是否正在寻找,但如果你想绑定到UserControls Dependency-Properties,请使用:

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

如果要绑定到UserControl的DataContext,请使用此绑定:

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

不是说我将UserControl指定为Ancestor-Type而不是您的具体类型(UserControl1)。