2013-10-12 128 views
0

我遇到過這個問題幾次,還沒有找到一個簡單的解決方案。當一個TextBlock(與TextWrapping="Wrap")嵌入另一個未指定其寬度的元素內時,TextBlock擴展的大小與其父級允許的一樣大,而不是首先嚐試包裝其文本。例如,我目前正在研究TextBlockValidationTemplate。這裏是模板目前如何處理文本比TextBox的寬度長:防止包裝TextBlock影響佈局

Current validation template

這顯然不是最佳的。這是我想它是如何出現:

Desired validation template

下面是對於用於生產第一佈局ControlTemplate的XAML:

<ControlTemplate> 
    <DockPanel LastChildFill="True"> 
    <Border DockPanel.Dock="Top" BorderBrush="Red" BorderThickness="1"> 
     <DockPanel> 
     <AdornedElementPlaceholder x:Name="TargetTextBox" /> 
     <Grid x:Name="WarningBoxContainer" Background="Red" Width="{Binding ElementName=TargetTextBox, Path=ActualHeight}" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}"> 
      <Path Margin="5" Stretch="Fill" Fill="#FFFFFFFF" Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z "/> 
     </Grid> 
     </DockPanel> 
    </Border> 
    <Border DockPanel.Dock="Top" Margin="0,2,0,0"> 
     <TextBlock Text="Something very terrible has happened" TextWrapping="Wrap"/> 
    </Border> 
    </DockPanel> 
</ControlTemplate> 

有誰知道如何試圖之前進行TextBlock包擴大?

回答

0

當然,我發佈後的幾分鐘內,我找到了答案。

我得到了使用綁定從this後強制執行TextBlock的寬度的想法。

以我的情況下,TextBlock的寬度結合AdornedElementPlaceholder元件的ActualWidth做到了:

<ControlTemplate> 
    <DockPanel LastChildFill="True"> 
    <Border DockPanel.Dock="Top" BorderBrush="Red" BorderThickness="1"> 
     <DockPanel> 
     <AdornedElementPlaceholder x:Name="TargetTextBox" /> 
     <Grid x:Name="WarningBoxContainer" Background="Red" Width="{Binding ElementName=TargetTextBox, Path=ActualHeight}" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}"> 
      <Path Margin="5" Stretch="Fill" Fill="#FFFFFFFF" Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z "/> 
     </Grid> 
     </DockPanel> 
    </Border> 
    <Border DockPanel.Dock="Top" Margin="0,2,0,0"> 
     <TextBlock Text="Something very terrible has happened" TextWrapping="Wrap" HorizontalAlignment="Left" Width="{Binding ElementName=TargetTextBox, Path=ActualWidth}" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}"/> 
    </Border> 
    </DockPanel> 
</ControlTemplate> 

最終產物:

enter image description here