使用 MVVM 的验证规则

发布于 2024-11-28 06:04:19 字数 292 浏览 2 评论 0原文

我有几个验证规则,我也使用 MVVM 。

我有一些“保存”按钮,并且仅当我没有任何数据网格行验证我的规则时才启用。

我应该如何在我的

        bool CanSaveChanges
        {
            get { return true; }
        }

datagrid 绑定到集合 public ICollectionView Customers

感谢帮助。

I have several Validation Rules , also I am using MVVM .

I have some "Save" button , and I want to enable in only when I don't have any datagridrows validating my rules.

How I should do in my

        bool CanSaveChanges
        {
            get { return true; }
        }

The datagrid is binded to collection public ICollectionView Customers

Thanks for help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

双马尾 2024-12-05 06:04:19

这是添加新客户屏幕的简单示例,我正在验证名称和电话。否,在 allPropertiesValid 属性设置为 true 之前,该按钮不会启用,这意味着所有验证都通过

View

<Window FlowDirection="RightToLeft" x:Class="GlassStore.AddNewSpecialCustomer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="clr-namespace:GlassStore.ViewModels"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AddNewSpecialCustomer" Height="346" Width="463" WindowStartupLocation="CenterScreen">

<Window.DataContext>
    <local:AddNewSpecialCustomerViewModel/>
</Window.DataContext>
<Grid Background="{DynamicResource NormalBrush}">
    <Button IsDefault="True" Command="{Binding Save}" Content="موافق" Height="39" HorizontalAlignment="Left" Margin="15,256,0,0" VerticalAlignment="Top" Width="76" />
    <Label Content="إسم العميل" Height="36" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="79" />
    <TextBox Text="{Binding specialCustomerName,Mode=TwoWay,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" Height="36" HorizontalAlignment="Left" Margin="111,12,0,0" VerticalAlignment="Top" Width="209" />
    <Label Content="المنطقة/المكان" Height="35" HorizontalAlignment="Left" Margin="12,67,0,0"  VerticalAlignment="Top" Width="94" />
    <TextBox Text="{Binding region}" Height="35" HorizontalAlignment="Left" Margin="111,67,0,0" VerticalAlignment="Top" Width="210" />
    <TextBox Text="{Binding tel,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" Height="33" HorizontalAlignment="Left" Margin="111,119,0,0" VerticalAlignment="Top" Width="210" />
    <Label Content="رقم الهاتف " Height="33" HorizontalAlignment="Left" Margin="12,119,0,0"  VerticalAlignment="Top" Width="94" />
    <Button IsCancel="True" Content="إلغاء" Height="39" HorizontalAlignment="Left" Margin="128,256,0,0" VerticalAlignment="Top" Width="78" />
    <Label Content="{Binding errorMessage}" ToolTip="{Binding richMessage}" Foreground="{Binding messageColor}" Height="40" HorizontalAlignment="Left" Margin="12,182,0,0"  VerticalAlignment="Top" Width="412" />
</Grid>
</Window>

ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Media;
namespace GlassStore.ViewModels
{
class AddNewSpecialCustomerViewModel:ViewModelBase,IDataErrorInfo
{
    private String _errorMessage;
    private Brush _messageColor;
    private String _richMessage;
    private String _specialCustomerName;
    private String _region;
    private String _tel;
    private bool _allPropertiesValid;
    private Dictionary<string, bool> validProperties;
    private Commands.RelayCommand _save;

    public AddNewSpecialCustomerViewModel()
    {

        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public String richMessage
    {

        get { return _richMessage; }
        set
        {
            if (_richMessage != value)
            {
                _richMessage = value;
                OnPropertyChanged("richMessage");
            }
        }
    }
    public String errorMessage
    {

        get { return _errorMessage; }
        set
        {
            if (_errorMessage != value)
            {
                _errorMessage = value;
                OnPropertyChanged("errorMessage");
            }
        }
    }

    public Brush messageColor
    {
        get
        {
            return _messageColor;
        }
        set
        {
            if (_messageColor != value)
            {
                _messageColor = value;
                OnPropertyChanged("messageColor");
            }

        }
    }

    public bool allPropertiesValid
    {

        get { return _allPropertiesValid; }
        set
        {
            if (_allPropertiesValid != value)
            {
                _allPropertiesValid = value;
              OnPropertyChanged("allPropertiesValid");                   
            }
        }
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }

    public ICommand Save
    {
        get
        {
            if (_save == null)
            {
                _save = new Commands.RelayCommand(param => CanAddSpecialCustomer(), param => AddSpecialCustomer());
            }

            return _save;
        }
    }



    public String region
    {
        get { return _region; }
        set
        {
            if (_region != value)
            {
                _region = value;
                OnPropertyChanged("region");

            }
        }
    }

    public String tel
    {
        get { return _tel; }
        set
        {
            if (_tel != value)
            {
                _tel = value;
               OnPropertyChanged("tel");
            }
        }
    }

    private bool CanAddSpecialCustomer()
    {
        return allPropertiesValid;
    }

    private void AddSpecialCustomer()
    {
        try
        {
            GlassStoreBLL.SpecialCustomer spcustomer = new GlassStoreBLL.SpecialCustomer();
            spcustomer.name = specialCustomerName;
            spcustomer.region = region;
            spcustomer.telNo = Int64.Parse(tel);
            spcustomer.AddNewCustomer(spcustomer);
            errorMessage = "نـجـاح";
            messageColor = Brushes.Green;
            region = "";
            tel = "";
            specialCustomerName = "";
        }
        catch (Exception d)
        {
            errorMessage = "خطأ أثناء تسجيل العميل الخاص";
            richMessage = d.Message;
            messageColor = Brushes.Red;
        }
    }


    string IDataErrorInfo.Error
    {
        get { return null; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            string error = String.Empty;
            switch (columnName)
            {
                case "specialCustomerName":
                    error = validateSpecialCustomerName();
                    validProperties["specialCustomerName"] = String.IsNullOrEmpty(error) ? true : false;
                    validateProperties();
                    return error;
                case "tel":
                    error = validateTel();
                    validProperties["tel"] = String.IsNullOrEmpty(error) ? true : false;
                    validateProperties();
                    return error;
                default:
                    throw new ApplicationException("Wrong Property name being validated");
            }
        }
    }

    private string validateSpecialCustomerName()
    {
        if (String.IsNullOrEmpty(specialCustomerName))
        {
            return "يجب إدخال إسم العميل الخاص";
        }
        else
        {
            if (specialCustomerName.Length < 2) return "إسم العميل الخاص لا يمكن أن يكون حرفين";
        }
        return String.Empty;
    }

    private string validateTel()
    {
        int result;
        if (int.TryParse(tel, out result))
        {
            if (tel.Count() < 6)
            {
                return "رقم التلفون لا يمكن أن يكون أقل من 6 أرقام";
            }
            else
            {
                if (result < 0)
                {
                    return "لا يمكن إدخال قيمة سالبة هنا";
                }
                return String.Empty;
            }
        }
        else
        {
            return "الرجاء إدخال أرقام فقط في رقم التلفون";
        }

    }

    private void validateProperties()
    {
        foreach (bool isValid in validProperties.Values)
        {
            if (isValid == false)
            {
                allPropertiesValid = false;
                return;
            }
        }
        allPropertiesValid = true;
    }
}
}

here a simple example of adding new customer screen , I'm validating the name and Tel.No, the button won't be enabled until allPropertiesValid property set to true , which means all validations are passed

View

<Window FlowDirection="RightToLeft" x:Class="GlassStore.AddNewSpecialCustomer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="clr-namespace:GlassStore.ViewModels"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AddNewSpecialCustomer" Height="346" Width="463" WindowStartupLocation="CenterScreen">

<Window.DataContext>
    <local:AddNewSpecialCustomerViewModel/>
</Window.DataContext>
<Grid Background="{DynamicResource NormalBrush}">
    <Button IsDefault="True" Command="{Binding Save}" Content="موافق" Height="39" HorizontalAlignment="Left" Margin="15,256,0,0" VerticalAlignment="Top" Width="76" />
    <Label Content="إسم العميل" Height="36" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="79" />
    <TextBox Text="{Binding specialCustomerName,Mode=TwoWay,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" Height="36" HorizontalAlignment="Left" Margin="111,12,0,0" VerticalAlignment="Top" Width="209" />
    <Label Content="المنطقة/المكان" Height="35" HorizontalAlignment="Left" Margin="12,67,0,0"  VerticalAlignment="Top" Width="94" />
    <TextBox Text="{Binding region}" Height="35" HorizontalAlignment="Left" Margin="111,67,0,0" VerticalAlignment="Top" Width="210" />
    <TextBox Text="{Binding tel,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" Height="33" HorizontalAlignment="Left" Margin="111,119,0,0" VerticalAlignment="Top" Width="210" />
    <Label Content="رقم الهاتف " Height="33" HorizontalAlignment="Left" Margin="12,119,0,0"  VerticalAlignment="Top" Width="94" />
    <Button IsCancel="True" Content="إلغاء" Height="39" HorizontalAlignment="Left" Margin="128,256,0,0" VerticalAlignment="Top" Width="78" />
    <Label Content="{Binding errorMessage}" ToolTip="{Binding richMessage}" Foreground="{Binding messageColor}" Height="40" HorizontalAlignment="Left" Margin="12,182,0,0"  VerticalAlignment="Top" Width="412" />
</Grid>
</Window>

ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Media;
namespace GlassStore.ViewModels
{
class AddNewSpecialCustomerViewModel:ViewModelBase,IDataErrorInfo
{
    private String _errorMessage;
    private Brush _messageColor;
    private String _richMessage;
    private String _specialCustomerName;
    private String _region;
    private String _tel;
    private bool _allPropertiesValid;
    private Dictionary<string, bool> validProperties;
    private Commands.RelayCommand _save;

    public AddNewSpecialCustomerViewModel()
    {

        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public String richMessage
    {

        get { return _richMessage; }
        set
        {
            if (_richMessage != value)
            {
                _richMessage = value;
                OnPropertyChanged("richMessage");
            }
        }
    }
    public String errorMessage
    {

        get { return _errorMessage; }
        set
        {
            if (_errorMessage != value)
            {
                _errorMessage = value;
                OnPropertyChanged("errorMessage");
            }
        }
    }

    public Brush messageColor
    {
        get
        {
            return _messageColor;
        }
        set
        {
            if (_messageColor != value)
            {
                _messageColor = value;
                OnPropertyChanged("messageColor");
            }

        }
    }

    public bool allPropertiesValid
    {

        get { return _allPropertiesValid; }
        set
        {
            if (_allPropertiesValid != value)
            {
                _allPropertiesValid = value;
              OnPropertyChanged("allPropertiesValid");                   
            }
        }
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }

    public ICommand Save
    {
        get
        {
            if (_save == null)
            {
                _save = new Commands.RelayCommand(param => CanAddSpecialCustomer(), param => AddSpecialCustomer());
            }

            return _save;
        }
    }



    public String region
    {
        get { return _region; }
        set
        {
            if (_region != value)
            {
                _region = value;
                OnPropertyChanged("region");

            }
        }
    }

    public String tel
    {
        get { return _tel; }
        set
        {
            if (_tel != value)
            {
                _tel = value;
               OnPropertyChanged("tel");
            }
        }
    }

    private bool CanAddSpecialCustomer()
    {
        return allPropertiesValid;
    }

    private void AddSpecialCustomer()
    {
        try
        {
            GlassStoreBLL.SpecialCustomer spcustomer = new GlassStoreBLL.SpecialCustomer();
            spcustomer.name = specialCustomerName;
            spcustomer.region = region;
            spcustomer.telNo = Int64.Parse(tel);
            spcustomer.AddNewCustomer(spcustomer);
            errorMessage = "نـجـاح";
            messageColor = Brushes.Green;
            region = "";
            tel = "";
            specialCustomerName = "";
        }
        catch (Exception d)
        {
            errorMessage = "خطأ أثناء تسجيل العميل الخاص";
            richMessage = d.Message;
            messageColor = Brushes.Red;
        }
    }


    string IDataErrorInfo.Error
    {
        get { return null; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            string error = String.Empty;
            switch (columnName)
            {
                case "specialCustomerName":
                    error = validateSpecialCustomerName();
                    validProperties["specialCustomerName"] = String.IsNullOrEmpty(error) ? true : false;
                    validateProperties();
                    return error;
                case "tel":
                    error = validateTel();
                    validProperties["tel"] = String.IsNullOrEmpty(error) ? true : false;
                    validateProperties();
                    return error;
                default:
                    throw new ApplicationException("Wrong Property name being validated");
            }
        }
    }

    private string validateSpecialCustomerName()
    {
        if (String.IsNullOrEmpty(specialCustomerName))
        {
            return "يجب إدخال إسم العميل الخاص";
        }
        else
        {
            if (specialCustomerName.Length < 2) return "إسم العميل الخاص لا يمكن أن يكون حرفين";
        }
        return String.Empty;
    }

    private string validateTel()
    {
        int result;
        if (int.TryParse(tel, out result))
        {
            if (tel.Count() < 6)
            {
                return "رقم التلفون لا يمكن أن يكون أقل من 6 أرقام";
            }
            else
            {
                if (result < 0)
                {
                    return "لا يمكن إدخال قيمة سالبة هنا";
                }
                return String.Empty;
            }
        }
        else
        {
            return "الرجاء إدخال أرقام فقط في رقم التلفون";
        }

    }

    private void validateProperties()
    {
        foreach (bool isValid in validProperties.Values)
        {
            if (isValid == false)
            {
                allPropertiesValid = false;
                return;
            }
        }
        allPropertiesValid = true;
    }
}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文