检查ObservableCollection是否有效

时间:2009-12-18 11:14:52

标签: wpf validation observablecollection

我有一个WPF Dev Express DxGrid,它以下列方式绑定到ObservableCollection。

Private _FamilyList As New ObservableCollection(Of FamilyRecord)
MyGrid.DataSource = _FamilyList

当用户开始在网格中输入信息时,我需要能够检查他们是否遗漏了一些信息,使其无效。

那么,检查_FamilyList没有验证错误的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我没有使用DevExpress网格的经验,但是在Xceed WPF DataGridControl上有一个名为UpdateSourceTrigger的属性,它控制数据源何时更新(当用户完成整行编辑时,完成编辑单元格,或每个键击)。我确信DevExpress也有类似的概念。

这将使您在验证发生时控制。您可以将数据验证逻辑放在FamilyRecord类本身中。当您检测到错误时,将FamilyRecord置于将在网格中提供视觉提示的错误状态。

修改

要在保存时确定您的收藏中是否有任何FamilyRecord个对象有任何错误,您需要这样的内容:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {

        ObservableCollection<FamilyRecord> _familyRecords;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _familyRecords = new ObservableCollection<FamilyRecord>();
            _familyRecords.Add(new FamilyRecord(@"Jones", false));
            _familyRecords.Add(new FamilyRecord(@"Smith", true));

            comboBox1.ItemsSource = _familyRecords;
        }

        // save button
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // validate whether any records still have errors before we save.
            if (_familyRecords.Any(f => f.HasErrors))
            {
                MessageBox.Show(@"Please correct your errors!");
            }
        }


    }

    public class FamilyRecord
    {

        public FamilyRecord(string name, bool hasErrors)
        {
            Name = name;
            HasErrors = hasErrors;
        }

        public string Name { get; set; }
        public bool HasErrors { get; set; }

        public override string ToString()
        {
            return this.Name;
        }
    }
}