PropertyChanged用于索引器属性 [英] PropertyChanged for indexer property

查看:127
本文介绍了PropertyChanged用于索引器属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有索引器属性的类,带有一个字符串键:

I have a class with an indexer property, with a string key:

public class IndexerProvider {
    public object this[string key] {
        get
        {
            return ...
        }
        set
        {
            ...
        }
    }

    ...
}

我使用索引器符号绑定到WPF中此类的一个实例:

I bind to an instance of this class in WPF, using indexer notation:

<TextBox Text="{Binding [IndexerKeyThingy]}">

工作正常,但我想提出一个 PropertyChanged 事件当其中一个索引器值更改。我尝试使用[keyname]的属性名称(即在键的名称附近包含[]),但这似乎不起作用。我没有在我的输出窗口中收到绑定错误。

That works fine, but I want to raise a PropertyChanged event when one of the indexer values changes. I tried raising it with a property name of "[keyname]" (i.e. including [] around the name of the key), but that doesn't seem to work. I don't get binding errors in my output window whatsoever.

我不能使用CollectionChangedEvent,因为索引不是基于整数的。在技​​术上,对象也不是一个集合。

I can't use CollectionChangedEvent, because the index is not integer based. And technically, the object isn't a collection anyway.

我可以这么做吗,而且如何?

Can I do this, and so, how?

推荐答案

根据这个博客条目,你必须使用Item []。 Item是编译器在使用索引器时生成的属性的名称。

According to this blog entry, you have to use "Item[]". Item being the name of the property generated by the compiler when using an indexer.

如果要显式,可以使用 IndexerName 属性。

If you want to be explicit, you can decorate the indexer property with an IndexerName attribute.

这样会使代码看起来像:

That would make the code look like:

public class IndexerProvider : INotifyPropertyChanged {

    [IndexerName ("Item")]
    public object this [string key] {
        get {
            return ...;
        }
        set {
            ... = value;
            FirePropertyChanged ("Item[]");
        }
    }
}

至少它使意图更清晰。我不建议您更改索引器名称,如果您的好友发现字符串Item []硬编码,这可能意味着WPF将无法处理具有不同的索引器名称。

At least it makes the intent more clear. I don't suggest you change the indexer name though, if your buddy found the string "Item[]" hard coded, it probably means that WPF would not be able to deal with a different indexer name.

这篇关于PropertyChanged用于索引器属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆