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

查看:28
本文介绍了索引器属性的 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.

这将使代码看起来像:

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天全站免登陆