我希望我的文本框根据验证状态显示特定文本作为工具提示。为此,我当前使用以下代码并且它有效:
<TextBox Name="textBox1">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="False">
<Setter Property="ToolTip" Value="{Binding XPath=HelpText/Description, Mode=OneTime}" />
</Trigger>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
如果没有错误,则会显示从 xml 文件读取的描述文本,如果有错误,则会显示验证错误字符串。
问题是,现在我必须复制此样式并将其应用到每个文本框(并更改 XPath,它对于每个文本框都是唯一的),我想要做的是将样式放在 Window.Resources 中,这样我可以为每个文本框引用它,如下所示:
<TextBox Name="textBox2" Style="{StaticResource TextBoxStyle}" />
但是每个文本框的 XPath 都不同,所以我不能只将样式放在 Window.Resources 中。如何使实例特定的 XPath 在样式中可用?有没有办法在不创建新文本框并从 TextBox 派生的情况下执行此操作?我想知道在这种情况下是否可以使用附加属性,但我不知道它们是如何工作的。
提前致谢。
最佳答案
我还没有完全测试过这个,但你可以使用附加属性 像这样的东西:
class ToolTipHelper {
public static readonly DependencyProperty ToolTipProperty =
DependencyProperty.RegisterAttached("ToolTip", typeof(string) ...
然后修改触发器:
<Trigger Property="Validation.HasError" Value="False">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(ToolTipHelper.ToolTip}, Mode=OneTime}" />
</Trigger>
你可以像这样使用它
<TextBox ToolTipHelper.ToolTip="{Binding XPath=HelpText/Description, Mode=OneTime}" />
关于带工具提示的 Wpf 文本框样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16060316/