将一个控件的值传递给转换器以设置另一个控件的宽度 [英] Pass the value of one control to a Converter to set the width on another control
问题描述
我要根据文本容器的宽度设置文本块的宽度,减去在文本块上设置的边距.
I want to set the width of a TextBlock based on the width of its container, minus the margins set on the TextBlock.
这是我的代码:
<TextBlock x:Name="txtStatusMessages"
Width="{Binding ElementName=LayoutRoot,Path=ActualWidth }"
TextWrapping="WrapWithOverflow"
Foreground="White"
Margin="5,5,5,5">This is a message
</TextBlock>
这很好用,除了由于将左右边距设置为5而导致TextBlock太大了10个单位之外.
And that works great except for the fact that the TextBlock is 10 units too big due to the Left and Right Margins bbeing set to 5.
好,所以我想...让我们使用转换器.但是我不知道如何传递我的容器控件的ActualWidth(见上:LayoutRoot).
OK, so I thought... Let's use a Converter. But I don't know how to pass the ActualWidth of my container control (SEE ABOVE: LayoutRoot).
我知道如何使用转换器,甚至是带有参数的转换器,只是没有像...这样的参数... Binding ElementName = LayoutRoot,Path = ActualWidth
I know how to use converters, and even converters with parameters, just not a parameter like... Binding ElementName=LayoutRoot,Path=ActualWidth
例如,我无法完成这项工作:
For example, I can't make this work:
Width="{Binding Converter={StaticResource PositionConverter},
ConverterParameter={Binding ElementName=LayoutRoot,Path=ActualWidth }}"
我希望我已经说得足够清楚了,希望您能有所帮助,因为Google今晚对我没有帮助.
I hope I made this clear enough and hope that you can help because Google is no help for me tonight.
推荐答案
您应该将另一个控件用作源,而不是参数. 该参数必须为常量,在您的情况下可以为-5.
you're supposed to use the other control as the source, not the parameter. The parameter has to be a constant and in your case can be -5.
我目前不在VS附近,因此语法可能不准确,但是它类似于:
I'm not near VS at the moment so the syntax maybe inaccurate, however, it is something like:
Width="{Binding ElementName=LayoutRoot, Path=ActualWidth,
Converter={StaticResource PositionConverter}, ConverterParameter=-5}"
(转换器将接收-5作为字符串,并且在使用前必须将其转换为数字.)
(The converter will receive -5 as a string and will have to convert it into a number before using it.)
根据我的经验,最好使用DependecyProperty XXX的OnXXXChanged回调,并且不要将同一窗口/根控件中的控件彼此绑定. 原因之一是您稍后可能希望将它们绑定到外部元素.
From my experience it is better to use the OnXXXChanged callback of DependecyProperty XXX, and not bind controls within the same window/root control one to another. One of the reasons for this is that you may want to bind them to an external element later on.
或者,使用多重绑定:
<TextBlock>
<TextBlock.Width>
<MultiBinding Converter="{StaticResource yourConverter}">
<MultiBinding.Bindings>
<Binding /> <!-- Bind to parameter 1 here -->
<Binding /> <!-- Bind to parameter 2 here -->
</MultiBinding.Bindings>
</MultiBinding>
</TextBlock.Width>
</TextBlock>
和一个将两个参数转换为所需值的转换器.
and and a converter which converts the two parameters to the value you want.
这篇关于将一个控件的值传递给转换器以设置另一个控件的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!