简体   繁体   English

DataGrid <-> ObservableCollection中的MVVM唯一列

[英]MVVM Unique column in DataGrid <-> ObservableCollection

My apologies if this question has been answered already. 抱歉,这个问题已经回答。 I've been struggling to figure out how to implement this and Google/StackOverflow searches haven't given me an answer that fits my needs. 我一直在努力寻找实现方法,而Google / StackOverflow搜索并没有给出适合我需求的答案。 To provide context to stuff like BindableBase -> I'm using Prism WPF 7.1 为诸如BindableBase之类的东西提供上下文->我正在使用Prism WPF 7.1

Model: 模型:

public class SampleModel : BindableBase
{
    private string _id;
    public string ID
    {
        get => _id;
        set => SetProperty(ref _id, value);
    }

    public string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public SampleModel()
    {
        ID = string.Empty;
        Name = string.Empty;
    }
}

View Model: 查看模型:

public class SampleViewModel
{
    public ObservableCollection<SampleModel> Collection { get; set; }

    public SampleModel SelectedEntry { get; set; }        

    public MainViewModel()
    {
        Collection = new ObservableCollection<SampleModel>();
    }
}

View: 视图:

<DataGrid Grid.Row="0"
        AutoGenerateColumns="False"
        ItemsSource="{Binding Collection}"
        SelectedItem="{Binding SelectedEntry}">
<DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding ID, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                        Header="ID"
                        Width="*"/>
    <DataGridTextColumn Binding="{Binding Name}"
                        Header="Name"
                        Width="*"/>
</DataGrid.Columns>

I would like to ensure that the cells of the WPF DataGrid goes red if the ID isn't unique. 如果ID不是唯一的 ,我想确保WPF DataGrid单元格变为红色。

The only solution I can think right now would be to add a pointer to the Collection<SampleModel> to every SampleModel instance, have SampleModel implement INotifyDataErrorInfo , and iterate looking for duplicate during System.ComponentModel.DataAnnotations.Validator.TryValidateProperty() (using a custom UniqueAttribute ). 我现在能想到的唯一解决方案是向每个SampleModel实例添加一个指向Collection<SampleModel>的指针,让SampleModel实现INotifyDataErrorInfo ,并在System.ComponentModel.DataAnnotations.Validator.TryValidateProperty()期间迭代查找重复项(使用自定义UniqueAttribute )。 However I'm worried that this wouldn't be the right solution since the Model would be coupled to the Collection that contains it. 但是我担心这不是正确的解决方案,因为模型将与包含它的集合耦合在一起。

public class UniqueAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Validate that property does not exist in collection?
    }
}

Does anyone know of a better way of implementing this? 有谁知道实现此目标的更好方法?

IMHO the best way to enforce uniqueness is to let the database do it. 恕我直言,实施唯一性的最佳方法是让数据库来做到这一点。 ID sounds like the primary key of your table, so the database will throw an exception if you try to create a duplicate. ID听起来像是表的主键,因此,如果您尝试创建重复项,数据库将引发异常。 Catch the error and turn it into a user friendly validation message. 捕获错误并将其转换为用户友好的验证消息。

If you rely on your UI, you run the risk of two users creating the same ID. 如果您依赖UI,则存在两个用户创建相同ID的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM