Binding vs MultiBinding => Different results

ぐ巨炮叔叔 提交于 2019-12-12 03:05:01

问题


I have a TextBlock inside a StackPanel. Since I'm using TextTrimming, I have to set manully the TextBox's width according the 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>

My converter:

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

Why is this working correctly and not that code below ? (using a IValueConverter with same code):

My converter can get the StackPanel but ActualWidth is always zero

<TextBlock.Width>

    <Binding RelativeSource="{x:Static RelativeSource.Self}" Path="TemplatedParent.Parent.ActualWidth"  Converter="{StaticResource WidthConverter}" />          
</TextBlock.Width>

回答1:


try

Width="{Binding Path=ActualWidth, 
                RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel}}"


来源:https://stackoverflow.com/questions/8909511/binding-vs-multibinding-different-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!