UserControl 的 DataContext [英] UserControl's DataContext

查看:33
本文介绍了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>

其中ColorText 是代码中定义的控件的依赖属性.这有效,但每次都指定 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">

并且没有指定 ElementNames,但这对我来说似乎也不是一个干净的解决方案.

and not specifying ElementNames, but that doesn't seem like a clean solution to me either.

我有两个问题:

  1. 为什么 不起作用?
  2. 做这样的事情最好的方法是什么?

推荐答案

对于第一个,尝试:

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

对于第二个问题,我认为使用 ElementNameAncestorBinding 是绑定到 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天全站免登陆