绑定到 ActualHeight 不起作用
我尝试创建一个具有半透明圆形背景的自定义控件:
<Canvas>
<TextBlock x:Name="StopText" Text="Some test text"/>
<Rectangle Fill="SkyBlue"
Width="{Binding Source=StopText, Path=ActualHeight}"
Height="20"
RadiusX="5" RadiusY="5" Opacity="0.2"/>
</Canvas>
问题是我可能无法绑定到 ActualHeight
/ActualWidth
属性,因为它们是不是依赖的。
如何保持矩形和文本框大小相同?
I tried to create a custom control, having a semitransparent rounded background:
<Canvas>
<TextBlock x:Name="StopText" Text="Some test text"/>
<Rectangle Fill="SkyBlue"
Width="{Binding Source=StopText, Path=ActualHeight}"
Height="20"
RadiusX="5" RadiusY="5" Opacity="0.2"/>
</Canvas>
The problem is that I can't, probably, bind to the ActualHeight
/ActualWidth
properties, cause they are not dependency ones.
What to do to mantain the rectangle and textbox of same size?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的绑定是在绑定到另一个元素时使用
ElementName
,而不是Source
:此外,您确实意识到您正在绑定
Rectangle
的宽度code> 到TextBlock
的Height
,对吧?如果这确实是您想要设置控件的方式,您将需要将
Rectangle
的宽度绑定到TextBlock
的ActualWidth
,并将高度
更改为ActualHeight
。更新
根据下面的评论,这是使用没有绑定的
Grid
的实现:Grid
和Canvas
使用不同的布局系统,并且由于您没有使用Canvas
提供的功能,因此Grid
是更好的选择。子元素的最大区别在于,
Rectangle
现在仅使用 Horizontal 和VerticalAlignment
在整个Grid
上进行Stretch
>,而不用担心任何东西的大小。The correct binding is to use
ElementName
, notSource
, when binding to another element:Also, you do realize that you are binding the width of the
Rectangle
to theHeight
of theTextBlock
, right?If this is really the way you want to set up your control, you will want to bind the
Rectangle
's Width to theTextBlock
'sActualWidth
, andHeight
toActualHeight
.UPDATE
Per the comments below, here is an implementation using a
Grid
with no binding:Grid
andCanvas
use different layout systems, and since you aren't using the functionality theCanvas
provides,Grid
is the better choice.The big difference in the child elements is that the
Rectangle
now just uses Horizontal andVerticalAlignment
toStretch
across the entireGrid
, instead of worrying about the sizes of anything.