2012-01-18 61 views
0

我在StackPanel內有TextBlock。由於我使用TextTrimming,因此我必須根據StackPanel.ActualWidth手動設置TextBox的寬度。綁定vs MultiBinding =>不同的結果

<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):

我的轉換器可以得到StackPanelActualWidth始終爲零

<TextBlock.Width> 

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

我認爲MultiBinding之後TextBlock的渲染製作,和(單)在TextBlok呈現之前進行綁定 – Avlin 2012-01-18 11:47:43

+0

您好,我可能遇到了同樣的問題,並且綁定了一個圖片源。我發佈了一個關於它的主題和一個小項目來測試:http://stackoverflow.com/questions/10128307/special-behavior-of-multibinding-vs-binding-when-specifying-an-imagesource – 2012-04-12 17:04:22

回答

0

嘗試

Width="{Binding Path=ActualWidth, 
       RelativeSource={RelativeSource FindAncestor, AncestorType=StackPanel}}" 
相關問題