Проверка контекста wpf - PullRequest
1 голос
/ 08 марта 2019

как заставить валидацию работать на ContentControl? Существует класс, который отвечает за сохранение значения с единицами измерения, он отображается в элементе управления содержимым через набор данных, я хотел бы проверить правильность при его отображении и редактировании, например, единицы не могут иметь значение 2 или значение должно быть меньше 10000. решить эту проблему с помощью мультисвязывания, при проверке значений правило проверки не выполняется.

Файл Xaml:

 <Window x:Class="DELETE1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:DELETE1"
            xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
            mc:Ignorable="d"
            x:Name="m_win"
            Title="MainWindow" Height="450" Width="800">
        <Window.Resources>
            <DataTemplate DataType="{x:Type local:ValWithUnits}">
                <Border>
                    <DockPanel>
                        <ComboBox DockPanel.Dock="Right" Width="60" IsEnabled="True" SelectedIndex="{Binding Unit}" ItemsSource="{Binding Src, ElementName=m_win}" />
                        <TextBox Text="{Binding Val,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  IsEnabled="True"/>
                    </DockPanel>
                </Border>
            </DataTemplate>
            <local:MultiBindingConverter x:Key="MultiBindingConverter" />
        </Window.Resources>
        <Grid>
            <ContentControl x:Name="m_contentControl">
                <ContentControl.Content>
                    <MultiBinding Mode="TwoWay"  NotifyOnValidationError="True" 
                                  UpdateSourceTrigger="PropertyChanged"
                                  diag:PresentationTraceSources.TraceLevel="High"
                                  Converter="{StaticResource MultiBindingConverter}" >
                        <Binding Path="Val" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" diag:PresentationTraceSources.TraceLevel="High"></Binding>
                        <Binding Path="Unit"  Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" diag:PresentationTraceSources.TraceLevel="High"></Binding>
                        <MultiBinding.ValidationRules>
                            <local:ContentControlValidationRule ValidatesOnTargetUpdated="True" x:Name="MValidationRule"/>
                        </MultiBinding.ValidationRules>
                    </MultiBinding>
                </ContentControl.Content>
            </ContentControl>
        </Grid>
    </Window>

И файл кода:

public class ValWithUnits:INotifyPropertyChanged
    {
        private double m_val;
        private int m_unit;
        public double Val
        {
            get => m_val;
            set
            {
                m_val = value;
                OnPropertyChanged(nameof(Val));
            }
        }
        public int Unit
        {
            get => m_unit;
            set
            {
                m_unit = value;
                OnPropertyChanged(nameof(Unit));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ValWithUnits MyValueWithUnits { get; set; } = new ValWithUnits();

        public MainWindow()
        {
            InitializeComponent();
            var a = new Binding("MyValueWithUnits");
            a.Source = this;
            a.ValidatesOnDataErrors = true;
            a.ValidatesOnExceptions = true;
            a.NotifyOnValidationError = true;
            m_contentControl.SetBinding(ContentControl.ContentProperty, a);

        }

        public IEnumerable<int> Src => new int[] { 1,2,3};
    }

    public class ContentControlValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            //Debug.Fail("validate");

            return ValidationResult.ValidResult;
        }

        private static ValidationResult BadValidation(string msg) =>
            new ValidationResult(false, msg);
    }


    public class MultiBindingConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return string.Format("{0}-{1}", values[0], values[1]);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return new object[] { 1, 1 };
        }
    }

Проверка 'ContentControlValidationRule', которую я устанавливаю через мультисвязывание, не работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...