WPF validation on one line?

I have already written several single-line links, and I would like to keep them that way, if possible, and if it is still publicly available. Is there any way to rewrite this

<TextBox.Text>
    <Binding Path="SomePath" NotifyOnValidationError="True" >
        <Binding.ValidationRules>
            <local:ValidationRule1></local:ValidationRule1>
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>

in one line ?, for example

<TextBox Text="{Binding Path=SomePath, [ValidationRule1...]}" />
+3
source share
2 answers

I think that there is not a single liner, and, in addition, the standard version is more readable.

0
source

There is no single line from the box, but it is quite possible to do it yourself using the markup extensions . In particular, create your own binding definition method for typical scenarios in your project.

, Binding , , ProvideValue. , , .

, , , :

using System;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;

namespace MyProject.Markup
{
    public class SingleValidationBindingExtension : MarkupExtension
    {
        private Binding _binding;

        public SingleValidationBindingExtension(Binding binding, ValidationRule validationRule)
        {
            _binding = binding;
            _binding.ValidationRules.Add(validationRule);
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _binding.ProvideValue(serviceProvider);
        }
    }
}

, - XAML:

<UserControl xmlns:ext="clr-namespace:MyProject.Markup;assembly=MyProject"
             ...>
    <UserControl.Resources>
        <local:ValidationRule1 x:Key="ValidationRule1"/>
    </UserControl.Resources>

    <!-- Note that you can customize other binding properties within the inner {Binding ...} markup -->
    <TextBox Text="{ext:SingleValidationBinding {Binding SomePath}, {StaticResource ValidationRule1}}" />

</UserControl>

! .

, . , . , , , , .

0

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


All Articles