[英]How to make custom template for validation rule's default tooltip?
使用验证规则时,如何为自动应用于控件的默认工具提示制作自定义模板? 还有有没有办法改变这个工具提示的持续时间?
我的意思是这个工具提示:
XAML:
<Window.Resources>
<!--Validation Template-->
<ControlTemplate x:Key="MyErrorTemplate">
<Border BorderBrush="#e92539" BorderThickness="2" CornerRadius="10">
<Grid>
<AdornedElementPlaceholder/>
</Grid>
</Border>
</ControlTemplate>
</Window.Resources>
<TextBox FontSize="13" Validation.ErrorTemplate="{StaticResource MyErrorTemplate}"
AcceptsReturn="False" Panel.ZIndex="3" x:Name="txtName"
Style="{StaticResource MyTextBox}" Grid.Row="2">
<TextBox.Text>
<Binding Path="txtName" Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnDataErrors="True">
<Binding.ValidationRules>
<local:ValidateTextBox/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
C#:
class ValidateTextBox : ValidationRule
{
Regex regex = new Regex(@"[\\/:*?""<>|]");
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string txtNameText = value as string;
if (regex.IsMatch(txtNameText))
{
return new ValidationResult(false, "A file name can't contain any of the following characters:\n \\ / : * ? \" < > |");
}
else
{
return new ValidationResult(true, null);
}
}
}
您必须调整您的TextBox
样式或创建一个新样式,它将ToolTip
设置为当前错误。
ToolTip
模板。ToolTipService
设置附加属性ShowDuration
,该属性确定工具提示应显示多长时间。 还有其他有用的属性需要探索。Validation.HasError
的Trigger
仅在出现错误时应用工具提示。 这允许您在不同的设置器中指定默认工具提示。ToolTip
与其关联控件不属于同一可视树的一部分,因此您必须使用绑定到其PlacementTarget
( TextBox)
,其中附加了验证错误。<Style x:Key="MyTextBox" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Validation.ErrorTemplate" Value="{StaticResource MyErrorTemplate}"/>
<Setter Property="ToolTipService.ShowDuration" Value="5000"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip">
<Setter.Value>
<ToolTip Template="{StaticResource ToolTipTemplate}"
Content="{Binding PlacementTarget.(Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource Self}}"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
您必须调整工具提示控件模板以将TextBlock
的Text
绑定到模板化父级( ToolTip
)的Content
属性。 这可以通过TemplateBinding
来完成。
<ControlTemplate x:Key="ToolTipTemplate" TargetType="ToolTip">
<Grid MaxWidth="400">
<Border Margin="0,0,35,35"
Background="#212529"
BorderBrush="#6C757D"
BorderThickness="1.7"
CornerRadius="5">
<Border.Effect>
<DropShadowEffect Color="Black"
Direction="310"
ShadowDepth="14"
BlurRadius="34"
Opacity="0.3"/>
</Border.Effect>
<TextBlock Margin="7"
Text="{TemplateBinding Content}"
VerticalAlignment="Top"
TextWrapping="Wrap"
HorizontalAlignment="Left"
Foreground="#ADB5BD">
</TextBlock>
</Border>
</Grid>
</ControlTemplate>
从TextBox
中删除Validation.ErrorTemplate
,因为它已经包含在样式中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.