Проверка списка элементов данных WPF MVVM - PullRequest
0 голосов
/ 09 февраля 2019

Я проверил отдельные элементы управления, такие как текстовое поле, выпадающий список, но застрял при попытке проверить элемент управления списком.

Код:

EntityBase.cs

public abstract class EntityBase : PropertyNotifier, IDataErrorInfo
    {
        #region IDataError implementation

        public virtual bool IsValid
        {
            get
            {
                return string.IsNullOrWhiteSpace(this.Error);
            }
        }

        public string Error { get; set; }

        public string this[string columnName]
        {
            get
            {
                this.Error = this.GetColumnValidated(columnName);
                this.OnPropertyChanged("IsValid");
                return this.Error;
            }
        }

        public virtual string GetColumnValidated(string columnName)
        {
            var info = this.GetType().GetProperty(columnName);
            if (info == null) return string.Empty;

            var customattributes = info.GetCustomAttributes(typeof(ValidationAttribute), false);
            if (customattributes.Length <= 0) return string.Empty;

            var descriptionAttributes = info.GetCustomAttributes(typeof(DescriptionAttribute), false);

            var value = Convert.ToString(info.GetValue(this, null));
            var validateAttribute = customattributes[0] as ValidationAttribute;

            if (validateAttribute == null || !validateAttribute.IsRequired || (this.GetType().GetProperty(columnName).PropertyType.Name == "Int32" && Convert.ToInt32(value) > 0) || (this.GetType().GetProperty(columnName).PropertyType.Name != "Int32" && !string.IsNullOrWhiteSpace(value)))
            {
                return string.Empty;
            }

            if (!string.IsNullOrEmpty(validateAttribute.ErrorMessage))
            {
                return validateAttribute.ErrorMessage;
            }
            else
            {
                var title = info.GetPropertyTitle(columnName);

                if (descriptionAttributes.Length > 0 && !string.IsNullOrEmpty((descriptionAttributes[0] as DescriptionAttribute).Description))
                {
                    title = (descriptionAttributes[0] as DescriptionAttribute).Description;
                }

                return string.Format("{0} is required", title);
            }
        }

В вышеприведенном классеЯ реализовал IDataErrorInfo для проверки.

CompanySettingModel.cs Это модель привязки, в которой мы должны проверять привязку списка ServiceSetting с помощью listbox.

public class CompanySettingModel : EntityBase
    {
        #region Variable Declaration

        private EmailTemplateModel emailTemplate;

        private int? companyEmailTemplateId;

        private string companyEmailTemplateName;

        private int? customerEmailTemplateId;

        private string customerEmailTemplateName;

        #endregion

        public CompanySettingModel()
        {
            this.emailTemplate = new EmailTemplateModel();
        }

        #region Public Properties

        public int Id { get; set; }

        [Validation(true)]
        public string CompanyName { get; set; }

        [Validation(true)]
        public string Address1 { get; set; }

        public string Address2 { get; set; }

        [Validation(true)]
        public string Country { get; set; }

        [Validation(true)]
        public int State { get; set; }

        [Validation(true)]
        public string City { get; set; }

        [Validation(true)]
        public string Zip { get; set; }

        public string SSN { get; set; }

        [Validation(true)]
        public string PhoneNumber { get; set; }

        public string FaxNo { get; set; }

        public string CompanyText { get; set; }

        [Validation(true)]
        public string EmailId { get; set; }

        public string WebSite { get; set; }

        public string UserName { get; set; }

        public string UserPassword { get; set; }

        public bool IsActive { get; set; }

        public int AutoPilotDays { get; set; }

        public bool IsAllMailsAndSMS { get; set; }

        public int NotificationType { get; set; }

        public string Type { get; set; }

        public string Licencekey { get; set; }

        public string CreatedOn { get; set; }

        public DateTime ModifiedDate { get; set; }

        public string ModifiedOn { get; set; }

        public int PaymentGatewayId { get; set; }

        public string LogoFullPath { get; set; }

        public string CompanyReceiptMessage { get; set; }

        public string CompanyReceiptSMS { get; set; }

        public string CustomerReceiptMessage { get; set; }

        public string CustomerReceiptSMS { get; set; }

        public int? CompanyEmailTemplateId
        {
            get
            {
                return companyEmailTemplateId;
            }
            set
            {
                companyEmailTemplateId = value;
                this.OnPropertyChanged(nameof(CompanyEmailTemplateId));
            }
        }

        public string CompanyEmailTemplateName
        {
            get
            {
                return companyEmailTemplateName;
            }
            set
            {
                companyEmailTemplateName = value;
                this.OnPropertyChanged(nameof(CompanyEmailTemplateName));
            }
        }

        public int? CustomerEmailTemplateId
        {
            get
            {
                return customerEmailTemplateId;
            }
            set
            {
                customerEmailTemplateId = value;
                this.OnPropertyChanged(nameof(CustomerEmailTemplateId));
            }
        }

        public string CustomerEmailTemplateName
        {
            get
            {
                return customerEmailTemplateName;
            }
            set
            {
                customerEmailTemplateName = value;
                this.OnPropertyChanged(nameof(CustomerEmailTemplateName));
            }
        }

        public string BannerImage { get; set; }

        public ObservableCollection<ServiceSettingModel> ServiceSetting { get; set; }

        public List<PaymentGatewayModel> PaymentGateways { get; set; }

        public BitmapImage EmailTemplateImage { get; set; }

        public EmailTemplateModel EmailTemplate
        {
            get
            {
                return emailTemplate;
            }
            set
            {
                emailTemplate = value;
                this.OnPropertyChanged(nameof(EmailTemplate));
            }
        }

        #endregion
    }

ServiceSettingModel.cs Эта модель, которую мы имеемпроверить, когда он связывается со списком в ObservableCollection в CompanySettingModel.

public class ServiceSettingModel : EntityBase
    {

        #region Private Variables

        private int? autoPilotRuleType;

        private int? notificationType;

        private int? emailTemplateId;

        private string emailTemplateName;

        #endregion

        #region Properties

        public long Id { get; set; }

        [Validation(true)]
        [Description("Rule Type")]
        public int? AutoPilotRuleType
        {
            get
            {
                return autoPilotRuleType;
            }
            set
            {
                autoPilotRuleType = value;
                this.OnPropertyChanged(nameof(AutoPilotRuleType));
            }
        }

        public string AutoPilotRuleTypeValue { get; set; }

        [Validation(true)]
        [Description("Rule Name")]
        public string RuleName { get; set; }

        [Validation(true)]
        public string Message { get; set; }

        public string SmsMessage { get; set; }

        [Validation(true)]
        public int? Days { get; set; }

        [Validation(true)]
        [Description("Notified By")]
        public int? NotificationType
        {
            get
            {
                return notificationType;
            }
            set
            {
                notificationType = value;
                this.OnPropertyChanged(nameof(NotificationType));
            }
        }

        public string NotificationTypeValue { get; set; }

        public int CompanyId { get; set; }

        public DateTime? ServiceStartDate { get; set; }

        public DateTime? ServiceEndDate { get; set; }

        public bool IsLinkAdd { get; set; }

        public bool IsRepeated { get; set; }

        public bool? IsDeleted { get; set; }

        public bool? IsActive { get; set; }

        public DateTime? CreatedDate { get; set; }

        public string Title { get; set; }

        public bool IsNotificationSent { get; set; }

        public int? EmailTemplateId {
            get
            {
                return emailTemplateId;
            }
            set
            {
                emailTemplateId = value;
                this.OnPropertyChanged(nameof(EmailTemplateId));
            }
        }

        public string EmailTemplateName {
            get
            {
                return emailTemplateName;
            }
            set
            {
                emailTemplateName = value;
                this.OnPropertyChanged(nameof(EmailTemplateName));
            }
        }

        #endregion

    }

Ниже приведен мой класс атрибута проверки, который я использовал для проверки

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ValidationAttribute : Attribute
    {

        public ValidationAttribute(bool isRequired)
        {
            this.IsRequired = isRequired;
        }

        public readonly bool IsRequired;

        public string ErrorMessage { get; set; }

        public bool IsValid
        {
            get
            {
                return !string.IsNullOrEmpty(this.ErrorMessage);
            }
        }
    }

Вот код xaml, в котором я имеюпроверить список, но не в состоянии его проверить.

<DataTemplate x:Key="serviceSettingsTemplate">
            <Grid Margin="0,0,0,10">
                <Border BorderBrush="Gray" BorderThickness="1" Background="White">
                    <Border.Effect>
                        <DropShadowEffect Color="Gray" ShadowDepth="2"/>
                    </Border.Effect>
                </Border>

                <Border BorderBrush="LightGray" BorderThickness="1">
                    <Grid Margin="10">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4.8*"></ColumnDefinition>
                            <ColumnDefinition Width="0.2*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>

                        <StackPanel Grid.Column="1" Orientation="Vertical" VerticalAlignment="Top" Margin="5">
                            <!--<MetroTheme:ModernButton Style="{StaticResource editButton}" Command="{Binding Path=DataContext.EditServiceSettingCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" CommandParameter="{Binding}" HorizontalAlignment="Right" Margin="0,0,0,10" />-->
                            <MetroTheme:ModernButton Style="{StaticResource removeButton}" Command="{Binding Path=DataContext.RemoveServiceSettingCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" CommandParameter="{Binding}" HorizontalAlignment="Right"  />
                        </StackPanel>

                        <Grid Grid.Column="0" HorizontalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition></ColumnDefinition>
                                <ColumnDefinition></ColumnDefinition>
                                <ColumnDefinition></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="30"/>
                                <RowDefinition Height="50"/>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="40"/>
                            </Grid.RowDefinitions>

                            <StackPanel Grid.Row="0" Grid.Column="0" Orientation="Horizontal" >
                                <Label Content="Rule Type: " FontWeight="Bold" VerticalAlignment="Center" />
                                <ComboBox ItemsSource="{Binding Path=DataContext.RuleTypeList, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" DisplayMemberPath="RoleType" SelectedValuePath="Id"
                              SelectedValue="{Binding Path=AutoPilotRuleType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
                                </ComboBox>
                            </StackPanel>

                            <StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal" Visibility="{Binding AutoPilotRuleType, Converter={StaticResource NotificationVisibilityConverter} }">
                                <Label Content="Notified After: " FontWeight="Bold" VerticalAlignment="Center"/>
                                <TextBox Text="{Binding Path=Days}" VerticalAlignment="Center" Width="30"></TextBox>
                                <TextBlock Text=" Days" VerticalAlignment="Center"></TextBlock>
                            </StackPanel>

                            <StackPanel Grid.Row="0" Grid.Column="2" Orientation="Horizontal" Visibility="{Binding AutoPilotRuleType, Converter={StaticResource NotificationVisibilityConverter} }">
                                <Label Content="Repeated: " FontWeight="Bold" VerticalAlignment="Center" />
                                <CheckBox IsChecked="{Binding Path=IsRepeated, Mode=TwoWay}" Margin="5,0,0,0" VerticalAlignment="Center" />
                            </StackPanel>

                            <StackPanel Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Orientation="Horizontal" Margin="0,8,8,8">
                                <Label Content="Rule Name: " FontWeight="Bold" VerticalAlignment="Center"/>
                                <StackPanel Orientation="Vertical" Width="550">
                                    <TextBox Text="{Binding Path=RuleName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TextWrapping="Wrap"></TextBox>
                                </StackPanel>
                            </StackPanel>
                            <StackPanel Grid.Row="2"  Grid.ColumnSpan="3" Orientation="Vertical" Margin="0,10,0,0" VerticalAlignment="Top" Visibility="{Binding NotificationType, Converter={StaticResource NotificationTypeVisibilityConverter}, ConverterParameter=email }">
                                <StackPanel  Orientation="Horizontal" VerticalAlignment="Top">
                                    <Label Content="Email:"  Margin="0,0,30,0" FontWeight="Bold"></Label>
                                    <TextBlock Name="Rule" Text="Rule" Visibility="Collapsed"></TextBlock>
                                    <TextBlock Name="MainEmail" Text="MainEmail" Visibility="Collapsed"></TextBlock>
                                    <TextBlock Name="Email" Text="Email" Visibility="Collapsed"></TextBlock>
                                    <TextBlock Name="RuleId" Text="{Binding Path=Id}" Visibility="Collapsed"></TextBlock>
                                    <TextBlock Name="EmailTemplateId" Text="{Binding Path=EmailTemplateId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Visibility="Collapsed"></TextBlock>
                                    <TextBlock Name="EmailTemplateName" Text="{Binding Path=EmailTemplateName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                                    <Button Margin="30,0,10,0" Content="View" Command="{Binding Path=DataContext.ShowTemplatePreviewCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" CommandParameter="{Binding Path=EmailTemplateId}"></Button>
                                    <Button Margin="10,0,0,0" Content="Customize" Command="{Binding Path=DataContext.EditEmailTemplateCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
                                        <Button.CommandParameter>
                                            <MultiBinding Converter="{StaticResource MultiParameterConverter}">
                                                <Binding Path="Text" ElementName="Rule"/>
                                                <Binding Path="Text" ElementName="RuleId"/>
                                                <Binding Path="Text" ElementName="EmailTemplateId"/>
                                                <Binding Path="Text" ElementName="EmailTemplateName" />
                                            </MultiBinding>
                                        </Button.CommandParameter>
                                    </Button>
                                </StackPanel>
                                <StackPanel Orientation="Horizontal" Margin="80,0,0,0">
                                    <Button Content="Select Template" Width="150" Command="{Binding Path=DataContext.GetEmailTemplateCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
                                        <Button.CommandParameter>
                                            <MultiBinding Converter="{StaticResource MultiParameterConverter}">
                                                <Binding Path="Text" ElementName="Rule"/>
                                                <Binding Path="Text" ElementName="RuleId"/>
                                                <Binding Path="Text" ElementName="MainEmail"/>
                                            </MultiBinding>
                                        </Button.CommandParameter>
                                    </Button>

                                    <Button Content="Copy from saved template" Width="200" Margin="10" Command="{Binding Path=DataContext.GetEmailTemplateCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
                                        <Button.CommandParameter>
                                            <MultiBinding Converter="{StaticResource MultiParameterConverter}">
                                                <Binding Path="Text" ElementName="Rule"/>
                                                <Binding Path="Text" ElementName="RuleId"/>
                                                <Binding Path="Text" ElementName="Email"/>
                                            </MultiBinding>
                                        </Button.CommandParameter>
                                    </Button>
                                </StackPanel>
                            </StackPanel>

                            <StackPanel Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3" Orientation="Horizontal" Visibility="{Binding NotificationType, Converter={StaticResource NotificationTypeVisibilityConverter}, ConverterParameter=sms }">
                                <Label Content="SMS: " FontWeight="Bold" VerticalAlignment="Top" />
                                <StackPanel Orientation="Vertical" Width="550">
                                    <TextBox Text="{Binding Path=SmsMessage}" 
                                             Height="170"
                                             Width="500"
                                             TextWrapping="Wrap" 
                                             AcceptsReturn="True"
                                             HorizontalScrollBarVisibility="Disabled"
                                             VerticalScrollBarVisibility="Auto"
                                             ></TextBox>
                                </StackPanel>
                            </StackPanel>

                            <StackPanel Grid.Row="4" Grid.Column="0" Orientation="Horizontal" Margin="5">
                                <Label Content="Notified By: " FontWeight="Bold" VerticalAlignment="Center" />
                                <ComboBox Grid.Row="4" Grid.Column="1" ItemsSource="{Binding Path=DataContext.NotificationTypeList, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" DisplayMemberPath="NotificationName" SelectedValuePath="Id"
                   SelectedValue="{Binding Path=NotificationType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
                            </StackPanel>

                            <StackPanel Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal">
                                <Label Content="Payment Link: " FontWeight="Bold" VerticalAlignment="Center"/>
                                <CheckBox IsChecked="{Binding Path=IsLinkAdd, Mode=TwoWay}"/>
                            </StackPanel>
                        </Grid>
                    </Grid>
                </Border>
            </Grid>
        </DataTemplate>

<ListBox Grid.Row="1" HorizontalAlignment="Stretch"
                        ItemsSource = "{Binding CompanySettings.ServiceSetting, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ItemContainerStyle="{StaticResource listBoxItem}"
                        ItemTemplate = "{StaticResource serviceSettingsTemplate}"/>

            <StackPanel Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Center">
                <Button  Content="Update" Width="100" Height="40" Margin="10" Command="{Binding UpdateCompanySettingsCommand}">
                    <Button.Style>
                        <Style BasedOn="{StaticResource BaseButtonStyle}" TargetType="Button">
                            <Setter Property="IsEnabled" Value="False" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=CompanySettings.ServiceSetting.IsValid}" Value="True">
                                    <Setter Property="IsEnabled" Value="True"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Button.Style>
                </Button>

            </StackPanel>

Я пробовал и гуглил получил одну ссылку на него, но не удовлетворен этим.Я не получил ответ, а также ответ не одобрен.Ссылка: StackOverFlow Ссылка на тот же вопрос, но не получен правильный ответ

Пожалуйста, помогите мне избавиться от этой проблемы проверки.

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