我TextBlock
内有StackPanel
。由于我正在使用TextTrimming
,因此我必须根据TextBox
手动设置StackPanel.ActualWidth
的宽度。
<StackPanel HorizontalAlignment="Stretch">
<TextBlock HorizontalAlignment="Left">
<TextBlock.Width>
<MultiBinding Converter="{StaticResource WidthConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}" />
<Binding RelativeSource="{x:Static RelativeSource.Self}" Path="TemplatedParent.Parent.ActualWidth" />
</MultiBinding.Bindings>
</MultiBinding>
</TextBlock.Width>
</TextBlock>
我的转换器:
Public Class WidthConverter
Implements IMultiValueConverter
Public Function Convert(ByVal values() As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert
Const TextBoxMarginRight As Double = 5
Dim ParentWidth As Double = CType(CType(values(0), FrameworkElement).Parent, FrameworkElement).ActualWidth
Dim ParentRelativeControlPosition As Point = CType(values(0), FrameworkElement).TransformToAncestor(CType(CType(values(0), FrameworkElement).Parent, Media.Visual)).Transform(New Point(0, 0))
Dim Width As Double = ParentWidth - TextBoxMarginRight - ParentRelativeControlPosition.X
If Width > 5 Then
Return Width
Else
Return 0
End If
End Function
为什么这样做正常而不是下面的代码? (使用具有相同代码的IValueConverter
):
我的转换器可以获得StackPanel
,但ActualWidth
始终为零
<TextBlock.Width>
<Binding RelativeSource="{x:Static RelativeSource.Self}" Path="TemplatedParent.Parent.ActualWidth" Converter="{StaticResource WidthConverter}" />
</TextBlock.Width>
答案 0 :(得分:0)
尝试
Width="{Binding Path=ActualWidth,
RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel}}"