用户控件中的数据上下文

发布于 2024-10-03 09:55:02 字数 710 浏览 8 评论 0原文

UserControls 中的DataContext 通常是如何设置的?如果我在我的用户控件、窗口或其他控件中执行类似以下操作,

DataContext = this

当我想要将控件与绑定一起使用时,我将必须有一个 RelativeSource 来指向 Window/UserControl

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

Is在UserControls中绑定控件的方式:在UserControls中设置使用RelativeSource而不是DataContext

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

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

碍人泪离人颜 2024-10-10 09:55:02

我不知道这是否是您正在寻找的,但如果您想绑定到 UserControls 依赖属性,请使用此:

<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 指定为祖先- 输入而不是您的具体类型 (UserControl1)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文