Getting focused element in WPF throgh XAML

I want to display errors (IDataErrorInfo.Errors) in one place on the screen, and not show the contents of the error next to. Therefore, for this, I placed a textBlock at the end of the form. How can I get the current lumped element for Binding (Validation.Errors) [0] .ErrorContent.

this should be done in XAML, not in code.

When the focus has changed, the content of this element is displayed in that the TextBlock is placed at the bottom of the screen.

Thanks and Regards Dineshbabu Sengottian

+3
source share
1 answer

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>

test 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: "Item []" ( "ValidationError" ) "(Validation.Errors)" ( "ReadOnlyObservableCollection`1" ). BindingExpression:. = (0) (1) [0].ErrorContent; DataItem = 'MainWindow' (Name= 'w'); "TextBlock" (Name= ''); target is 'Text' (type 'String') ArgumentOutOfRangeException: 'System.ArgumentOutOfRangeException: .

, , Validation.Errors , [0] .

( ), - , , . , IInputElement, FocusManager.FocusedElement .

+3

All Articles