Skip to main content
 首页 » 编程设计

c#之绑定(bind)自定义类中的键

2024年02月13日19unruledboy

是否可以像 Dictionary 那样在自定义类中绑定(bind) Key?

我可以使用此绑定(bind)绑定(bind)到 Dictionary:

"Binding MyDictionary[MyKey]"  

但我不想使用 Dictionary 而是像这样的自定义类:

public class DataGridField :  INotifyPropertyChanged 
{ 
    [Required] 
    [Key] 
    public string Key { get; set; } 
 
    private object value; 
    public object Value 
    { 
        get 
        { 
            return this.value; 
        } 
        set 
        { 
            this.value = value; 
            this.OnPropertyChanged("Value"); 
        } 
    } 
} 

现在我想访问 ObservableCollection 中此类的对象,就像我访问 Dictionary 一样。 有什么办法可以做到这一点吗?

请您参考如下方法:

可以,但必须执行 indexer property :

public class DataGridField 
{ 
    public string this[string index] 
    { 
        get { return this.Key; } 
        set 
        { 
            this.Key = index; 
        } 
     } 
 } 

编辑:

但是如果您有兴趣使用带有 INotifyProperty/CollectionChange 实现的 Dictionary,您可以使用 ObservableDictionary