UserControls中的DataContext [英] DataContext in UserControls

查看:106
本文介绍了UserControls中的DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

DataContext = this

在我的窗口或其他控件中,如果要使用带有绑定的控件,则必须有一个 RelativeSource 指向窗口/用户控件

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}}}" />

是在UserControls中绑定控件的方法:设置use RelativeSource ,而不是 DataContext

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>


推荐答案

如果您正在寻找它,我不知道,但是如果要绑定到UserControls依赖项属性,请使用以下方法:

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>

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

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>

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

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

这篇关于UserControls中的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆