Отключить добавление границ в пользовательском контроле при проверке - PullRequest
0 голосов
/ 12 ноября 2018

Когда я пытаюсь проверить поле, у меня есть границы для всего пользовательского контроля.Я не понимаю, почему?

Как вы можете добавить, что текстовое поле всплывающей подсказки может не перекрываться?

Я новичок в C #, так что, если вы мне поможете, это будет ужасно

экран

Вы можете увидеть мой код:

Вы можете увидеть код для модели проверки:

namespace BBS.CaseDetails.Operator.ViewModel
{
    public abstract class ValidationModel : ViewModelBase, INotifyDataErrorInfo
    {
        private Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        private object threadLock = new object();
        public bool IsValid
        {
            get { return !this.HasErrors; }

        }

        public void OnErrorsChanged(string propertyName)
        {
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        public IEnumerable GetErrors(string propertyName)
        {
            if (!string.IsNullOrEmpty(propertyName))
            {
                if (errors.ContainsKey(propertyName) && (errors[propertyName] != null) && errors[propertyName].Count > 0)
                    return errors[propertyName].ToList();
                else
                    return null;
            }
            else
                return errors.SelectMany(err => err.Value.ToList());
        }

        public bool HasErrors
        {
            get { return errors.Any(propErrors => propErrors.Value != null && propErrors.Value.Count > 0); }
        }

        public void ValidateProperty(object value, [CallerMemberName] string propertyName = null)
        {
            lock (threadLock)
            {
                var validationContext = new ValidationContext(this, null, null);
                validationContext.MemberName = propertyName;
                var validationResults = new List<ValidationResult>();
                Validator.TryValidateProperty(value, validationContext, validationResults);

                //clear previous errors from tested property
                if (errors.ContainsKey(propertyName))
                    errors.Remove(propertyName);
                OnErrorsChanged(propertyName);

                HandleValidationResults(validationResults);
            }
        }

        public void Validate()
        {
            lock (threadLock)
            {
                var validationContext = new ValidationContext(this, null, null);
                var validationResults = new List<ValidationResult>();
                Validator.TryValidateObject(this, validationContext, validationResults, true);

                //clear all previous errors
                var propNames = errors.Keys.ToList();
                errors.Clear();
                propNames.ForEach(pn => OnErrorsChanged(pn));

                HandleValidationResults(validationResults);
            }
        }

        private void HandleValidationResults(List<ValidationResult> validationResults)
        {
            //Group validation results by property names
            var resultsByPropNames = from res in validationResults
                                     from mname in res.MemberNames
                                     group res by mname into g
                                     select g;

            //add errors to dictionary and inform  binding engine about errors
            foreach (var prop in resultsByPropNames)
            {
                var messages = prop.Select(r => r.ErrorMessage).ToList();
                errors.Add(prop.Key, messages);
                OnErrorsChanged(prop.Key);
            }
        }
    }
}

Вы можете видеть, что нет границы для запроса usercontrool, но когда я пытаюсь подтвердить, он появляется код xaml:

<UserControl x:Class="BBS.CaseDetails.Operator.View.CaseInformationView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:resx="clr-namespace:BBS.Resource.Properties;assembly=BBS.Resource"
             mc:Ignorable="d" >
    <UserControl.Resources>
        <Style TargetType="TextBox">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <StackPanel>
                            <Border BorderThickness="2" BorderBrush="DarkRed">
                                <StackPanel>
                                    <AdornedElementPlaceholder    
                                x:Name="errorControl" />
                                </StackPanel>
                            </Border>
                            <TextBlock Text="{Binding AdornedElement.ToolTip    
                        , ElementName=errorControl}" Foreground="Red" />
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="BorderBrush" Value="Red" />
                    <Setter Property="ToolTip"    
                Value="{Binding RelativeSource={RelativeSource Self}    
                    , Path=(Validation.Errors)/ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1.5*" />
            <ColumnDefinition Width="4*" />
        </Grid.ColumnDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Content="{x:Static resx:CaseDetails.CaseInformation}" FontWeight="Bold"/>
        <Label Grid.Row="1" Grid.Column="0" Content="{x:Static resx:CaseDetails.SteriaFitPlusOperator}"/>
        <Label Grid.Row="2" Grid.Column="0" Content="{x:Static resx:CaseDetails.TransactionCaseType}"/>
        <Label Grid.Row="3" Grid.Column="0" Content="{x:Static resx:CaseDetails.IncidentNumber}"/>
        <Label Grid.Row="4" Grid.Column="0" Content="{x:Static resx:CaseDetails.IncidentDate}"/>
        <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding SteriaFitPlusOperator,UpdateSourceTrigger=PropertyChanged , Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnNotifyDataErrors=True}">

        </TextBox>

        <ComboBox Grid.Column="1"  Height="auto"  Grid.Row="2"  Width="100"  ItemsSource="{Binding TransactionType,UpdateSourceTrigger=PropertyChanged , Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnNotifyDataErrors=True}"  SelectedItem="{Binding TransactionTypeItem}"/>
        <TextBox Grid.Column="1" Grid.Row="3" Text="{Binding IncidentNumber, UpdateSourceTrigger=PropertyChanged , Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnNotifyDataErrors=True}"   >

        </TextBox>
        <DatePicker Grid.Column="1" Grid.Row="4" SelectedDate="{Binding IncidentDate, UpdateSourceTrigger=PropertyChanged , Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnNotifyDataErrors=True }"  />

    </Grid>
</UserControl>

это пример поля, которое я пытаюсь проверить модель валидации:

[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "Required")]
        [MaxLength(50, ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "MaxLength")]
        [MinLength(3, ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "MinLength")]
        public string SteriaFitPlusOperator
        {
            get => _caseInformation.SteriaFitPlusOperator;
            set
            {
                if (_caseInformation.SteriaFitPlusOperator == value)
                    return;
                _caseInformation.SteriaFitPlusOperator = value;
                ValidateProperty(value);
                RaisePropertyChanged("SteriaFitPlusOperator");
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...