UserControl的DataContext [英] UserControl's DataContext

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

问题描述

我正在创建 UserControl 我想使用类似这样的东西:

I'm creating a UserControl I want to use something like this:

<controls:ColorWithText Color="Red" Text="Red color" />

到目前为止,我已经实现了类似的控件:

So far, I've implemented similar controls like this:

<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
    <StackPanel Orientation="Horizontal" >
        <Border Width="15" Height="15" Background="{Binding Color, ElementName=ThisControl}" />
        <TextBlock Text="{Binding Text, ElementName=ThisControl}" />
    </StackPanel>
</UserControl>

其中颜色 Text 是代码中定义的控件的依赖属性。可以,但是每次都指定 ElementName 似乎是不必要的。

where Color and Text are dependency properties of the control defined in code. This works, but specifying ElementName every time seems unnecessary.

另一个可行的选择是使用

Another option that works is using

<UserControl x:Class=… DataContext="{Binding ElementName=ThisControl}" Name="ThisControl">

并且未指定 ElementName s,但是

我有两个问题:


  1. 为什么< UserControl DataContext = {RelativeSource Self}}> 不起作用?

  2. 最好的方式来做这样的事情?

  1. Why doesn't <UserControl DataContext="{RelativeSource Self}"> work?
  2. What is the best way to do something like this?


推荐答案

对于第一个,请尝试:

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">

对于第二个问题,我认为使用 ElementName AncestorBinding 是绑定到 UserControl 的属性的最佳方法。

And for second question, I think using ElementName or AncestorBinding is best way to bind to UserControl's properties.

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

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