3

我想在屏幕的一个位置显示错误(IDataErrorInfo.Errors),而不是在附近显示错误内容。因此,我已将 textBlock 放在表单的末尾。如何获取当前的焦点元素以进行绑定(验证.Errors)[0].ErrorContent。

这应该在 XAML 中完成,而不是在后面的代码中。

当焦点更改时,该元素的错误内容将显示在放置在屏幕底部的 TextBlock 中。

感谢和问候 Dineshbabu Sengottian

4

1 回答 1

3

您可以使用 访问焦点元素FocusManager.FocusedElement。这是一个纯粹使用 XAML 的示例,没有任何代码隐藏(当然,提供IDataErrorInfo测试错误所需的代码隐藏除外):

<Window x:Class="ValidationTest.MainWindow"
        x:Name="w"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel>
        <TextBox x:Name="txt1" Text="{Binding Path=Value1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, Mode=TwoWay}"/>
        <TextBox x:Name="txt2" Text="{Binding Path=Value2, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, Mode=TwoWay}"/>
        <TextBlock Foreground="Red" Text="{Binding 
                        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, 
                        Path=(FocusManager.FocusedElement).(Validation.Errors)[0].ErrorContent}"/>
    </StackPanel>
</Window>

测试类MainWindow有以下代码:

namespace ValidationTest
{
    public partial class MainWindow : Window, IDataErrorInfo
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;

            Value1 = "a";
            Value2 = "b";
        }

        public string Value1 { get; set; }
        public string Value2 { get; set; }

        #region IDataErrorInfo Members

        public string Error
        {
            get { return ""; }
        }

        public string this[string name]
        {
            get
            {
                if (name == "Value1" && Value1 == "x")
                {
                    return "Value 1 must not be x";
                }
                else if (name == "Value2" && Value2 == "y")
                {
                    return "Value 2 must not be y";
                }
                return "";
            }
        }

        #endregion
    }
}

对于测试,如果在第一个文本框中输入“x”或在第二个文本框中输入“y”,则会出现验证错误。

当前焦点文本框的错误消息出现在 TextBlock 中的两个文本框下方。

请注意,此解决方案有一个缺点。如果您在调试器下运行示例,您将看到这些绑定错误:

System.Windows.Data 错误:17:无法从“(Validation.Errors)”(类型“ReadOnlyObservableCollection`1”)获取“Item []”值(类型“ValidationError”)。BindingExpression:Path=(0).(1)[0].ErrorContent; DataItem='MainWindow' (Name='w'); 目标元素是'TextBlock'(名称='');目标属性是“文本”(类型“字符串”) ArgumentOutOfRangeException:“System.ArgumentOutOfRangeException:指定的参数超出了有效值的范围。

这些调试错误消息发生在当前焦点元素没有验证错误时,因为Validation.Errors数组是空的,因此[0]是非法的。

您可以选择忽略这些错误消息(示例仍然运行良好),或者您仍然需要一些代码隐藏,例如将IInputElement返回的 from转换FocusManager.FocusedElement为字符串的转换器。

于 2012-05-13T08:52:52.070 回答