我正在尝试为我的控件SuperTextB编写一个模板,在控件的TextBox的整个区域上设置一个矩形。当验证失效时,此矩形将用于显示验证错误消息,并将在其余时间隐藏。我试图做的是,但它确实没有用。
<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 :(得分:1)
您不需要所有这些宽度和高度绑定。用网格替换Canvas,然后按顺序将TextBox和Rectangle设置为Grid子项。 ZIndex将自动使矩形显示在顶部。将Rectangle背景设置为null或将其设置为Hidden,直到您准备好显示它为止。例如:
<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>