Why are my validation rules not executed when setting the DataContext?

I have the following Loaded event in my window:

void Window_Loaded(object sender, RoutedEventArgs e) {
    this.DataContext = new MyObject() {
        MyDateTime = DateTime.Now,
        MyNotEmptyString = "Not Empty",
        MyNotUpperCaseString = "not upper case",
        MyInteger = 20,
        MyIntegerInRange = 1,
        MyDouble = 4.56
    };
}

For each property initialized above, I bind to it TextBox, each of which has its own validation rule associated with it.

The problem is that my Validation Rules do not start the first time they are installed this.DataContext, but they work fine when the form is used normally (they start when it TextBoxloses focus). What could be the reason for this? I tried to install UpdateSourceTrigger="PropertyChanged", but that did not help.

Edit: Here is an example TextBoxthat is bound to a property:

<TextBox Name="MyDoubleField">
    <TextBox.Text>
        <Binding Path="MyDouble">
            <Binding.ValidationRules>
                <local:TextIsDouble/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
+3
3

"" : . , .

, : . , , , WPF - WinForms Validate().

+3

, ? IDataErrorInfo , - .

, , , WPF.

0

, DataContext, , WPF , (AKA, ).

DataContext, , , BindingExpression, UpdateSource. .

, - :

    private void ValidateData()
    {            
        //The XAML file defines a group of TextBox elements inside a Grid called grd
        foreach (UIElement uie in grd.Children)
        {
            if (uie.GetType() == typeof(TextBox))
            {
                ((TextBox)uie).GetBindingExpression(TextBox.TextProperty).UpdateSource();          
            }
        }                    
    }
0

Source: https://habr.com/ru/post/1712770/


All Articles