2011-07-07 54 views
0

我想爲我的控件SuperTextB編寫一個模板,在控件的TextBox的整個區域設置一個矩形。當驗證失敗時,此矩形將用於顯示驗證錯誤消息,並且在剩餘時間內將被隱藏。我試圖做的事情如下,但它並沒有真正奏效。Generic.xaml爲矩形垂直堆疊在上面的文本框?

<ResourceDictionary 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:SuperTB"> 
<Style TargetType="{x:Type local:SuperTextB}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:SuperTextB}"> 
       <Border Background="{TemplateBinding Background}" 
        BorderBrush="{TemplateBinding BorderBrush}" 
        BorderThickness="{TemplateBinding BorderThickness}"> 
        <Canvas x:Name="painting" Background="Red" 
          Height="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Height}" 
           Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Width}"> 
         <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus }" x:Name="PART_input" 
           Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas, AncestorLevel=1}, Path=Height}" 
           Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas, AncestorLevel=1}, Path=Width}" 
           Canvas.ZIndex="1"/> 
         <Rectangle x:Name="PART_error" 
           Height="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas, AncestorLevel=1}, Path=Height}" 
           Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas, AncestorLevel=1}, Path=Width}" 
           Canvas.ZIndex="2"/> 
        </Canvas> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

+0

您可以擴展「它沒有真正的工作嗎?」有什麼問題? – itowlson

回答

1

你並不需要所有這些寬度和高度綁定。用網格替換畫布,然後按照該順序將TextBox和Rectangle設置爲Grid子元素。 ZIndex會自動使矩形顯示在最上面。將矩形背景設置爲空或將其設置爲隱藏,直到您準備好顯示它。例如:

<Style TargetType="{x:Type local:SuperTextB}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:SuperTextB}"> 
       <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> 
        <Grid x:Name="painting" Background="Red"> 
         <TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, Mode=TwoWay, UpdateSourceTrigger=LostFocus }" x:Name="PART_input"/> 
         <Rectangle x:Name="PART_error" Visibility="Hidden"/> 
        </Grid> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
+0

輝煌,謝謝! – humanstory