【问题标题】:Binding to (Validation.Errors).CurrentItem does not work with TextBox (works with DataGrid)绑定到 (Validation.Errors).CurrentItem 不适用于 TextBox(适用于 DataGrid)
【发布时间】:2011-07-26 03:30:25
【问题描述】:

我正在尝试将 ToolTip 属性绑定到代码中的 (Validation.Errors).CurrentItem。我已经用 DataGrid 做到了,比如:

var grid = new FrameworkElementFactory(typeof(Grid));
grid.SetValue(Grid.ToolTipProperty, new Binding() {
        RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridRow), 1),
        Path = new PropertyPath("(Validation.Errors).CurrentItem.ErrorContent")
});

这行得通,错误符号出现在带有工具提示的行标题中(一些错误文本)。

当我尝试对文本框执行相同操作时,工具提示不会出现:

grid.SetValue(Grid.ToolTipProperty, new Binding() {
     ElementName = textBox1.Name, // tried with relative source also...
     Path = new PropertyPath("(Validation.Errors).CurrentItem.ErrorContent")
});

问候,

【问题讨论】:

  • TextBox 是在网格内(我的意思是在单元格内)还是在网格外?
  • 网格只是错误标志的基础。所以工具提示是在一个网格上......

标签: c# wpf validation binding


【解决方案1】:

看起来您可以使用Binding.Source 属性。像这样:

grid.SetValue(Grid.ToolTipProperty, new Binding() {
     Source = textBox1,
     Path = new PropertyPath("(Validation.Errors).CurrentItem.ErrorContent")
});

【讨论】:

    【解决方案2】:

    我不确定您是否需要其中的 CurrentItem

    我以前从未在代码中完成验证绑定,但我的用于 TextBox 验证的 XAML 如下所示:

    <Style TargetType="{x:Type TextBox}" x:Key="ValidatingTextBox">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Setter Property="ToolTip" Value="{Binding 
                        Path=(Validation.Errors)[0].ErrorContent, 
                        RelativeSource={x:Static RelativeSource.Self}}" />
            </Trigger>
        </Style.Triggers>
    </Style>
    

    【讨论】:

    • 是的,它绑定到 TextBox 本身,但我想绑定到放置在 TextBox 附近的错误符号(内部带有 Ellipse 和 TextBlock 的网格,看起来像 (!) )
    • @Vale 在触发器中设置模板而不是工具提示并覆盖它以显示您的网格和椭圆
    • @Rachel:当没有验证错误时,CurrentItem 允许您在控制台中绑定并且不会出现错误。见stackoverflow.com/questions/2260616/…
    猜你喜欢
    • 2016-02-24
    • 2012-03-24
    • 2012-09-01
    • 2023-03-07
    • 2020-08-17
    • 2017-06-19
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多