限制 ObservableCollection<T> 中的数据

Restrict data in the ObservableCollection<T>

如果我的方法有问题,请告诉我。 我有一个包含数据网格的 WPF window。这是为了让用户输入要处理的程序的对象 ID 列表。

我将 DataGrid 的 ItemsSource 绑定到一个 ObservableCollection,其中 MyObject 是一个 class 和一个字符串 属性 - ObjectId。

我有一个集合更改时间的事件:

 void TasksList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            ProgressBarMax = TasksList.Count;
            TaskCountLabel = string.Format("{0} tasks to modify", TasksList.Count);
        }

我还想验证输入的数据 - 用户可能提供了不正确的 ID,在这种情况下我不想将其添加到集合中。 但是,当我访问 e.NewItems[0] 对象时,它的 ObjectId 属性 仍然是 null,所以我无法验证。

我的方法有什么问题?

根据评论添加数据网格 XAML:

<DataGrid Margin="5,0,5,10"
                                         ColumnWidth="*"
                                         ItemsSource="{Binding ElementName=ThisUc,
                                                               Path=TasksList,
                                                               Mode=TwoWay,
                                                               UpdateSourceTrigger=PropertyChanged}"
                                         Style="{x:Null}"
                                         CanUserAddRows="True" CanUserPasteToNewRows="True"
                                         x:Name="TasksDataGrid"
                                         CanUserDeleteRows="True"
                                         VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
                                         SelectionUnit="Cell" />

I would also like to validate the data on input

只需使用 WPF 验证功能。例如,基于 IDataErrorInfo 的验证:

public class RowViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    // INPC implementation is omitted

    public string Id
    {
        get { return id; }
        set
        {
            if (id != value)
            {
                id = value;
                OnPropertyChanged();
            }
        }
    }
    private string id;

    public string this[string columnName]
    {
        get
        {
            if (string.IsNullOrEmpty(Id))
            {
                return "Id cannot be an empty string.";
            }

            return null;
        }
    }

    public string Error
    {
        get { return null; }
    }
}

    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Rows}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Id" Binding="{Binding Id, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
        </DataGrid.Columns>
    </DataGrid>

the user might provide an incorrect Id, in which case I don't want to add it to the collection

你不能。

DataGrid 使用就地编辑时,添加新行会自动将新项目添加到绑定 ItemsSource 中。但是,如果行数据源使用验证,则在出现验证错误之前,用户无法提交更改。

在这种情况下,用户只有一种方法可以取消编辑,当他取消时,DataGrid 从基础 ItemsSource 中删除新行。