【问题标题】:Property setter not getting called with CollectionEditor没有使用 CollectionEditor 调用属性设置器
【发布时间】:2011-04-14 15:52:44
【问题描述】:

我有一个具有Items 属性的自定义控件。我已经应用了 EditorAttributeUITypeEditor 类型的 CollectionEditor

收藏类型:

[Serializable]
[Editor(typeof(CollectionEditor), typeof(UITypeEditor))]
public class ListItemsCollection : CollectionBase
{
    // methods
}

控件中的属性声明:

private new ListItemsCollection _Items;

[Editor(typeof(CollectionEditor), typeof(UITypeEditor))]
public new ListItemsCollection Items
{
    get
    {
        return _Items;
    }
    set
    {
        _Items = value;

        // do other UI changes
    }
}

问题:
当我将此控件放到设计器表面时,我可以使用 PropertyGrid 将项目添加到 Items 属性。但是,当我单击CollectionEditorOk 按钮时,Items 属性的设置器没有被调用。

当从UITypeEditor 类的EditValue 方法返回值时,应该调用属性的设置器块。

这让我发疯了。我什至尝试将Event添加到ListItemsCollection,这样当添加项目时,我可以使用控件的ui来做任何我想要的事情。

这应该不难。我做错了什么?

【问题讨论】:

    标签: c# winforms uitypeeditor collectioneditor


    【解决方案1】:

    我尝试重现您的情况:使用以下代码,每当我从 VS 属性窗口编辑列表时,都会显示一个消息框。请注意,您必须自己创建列表。如果你不创建它,VS 创建一个临时列表,你可以从属性窗口编辑它,但不会将你的属性设置到这个列表(所以你的 setter 永远不会被调用)

        public UserControl1()
        {
            InitializeComponent();
            list = new BindingList<ListViewItem>();
            list.ListChanged += new ListChangedEventHandler(list_ListChanged);
        }
    
        void list_ListChanged(object sender, ListChangedEventArgs e)
        {
            MessageBox.Show(e.ListChangedType.ToString());
        }
    
        private BindingList<ListViewItem> list;
    
        public BindingList<ListViewItem> List1
        {
            get { return list; }
        }
    

    【讨论】:

    • BindingList 工作正常......但我必须扩展 BindingList 和 CollectionEditor 以便在单击 OK 按钮后引发 ListChanged 事件。
    【解决方案2】:

    集合属性应该是只读的。它是通过 getter 检索并调整的集合。 setter 永远不会进入它,因为这意味着设置一个新的集合。

    【讨论】:

    • 使用CollectionEditor修改收藏时如何进行某些操作?
    • 您只能知道您的集合本身是否有任何事件,这种情况并不常见,而且绝对不在 ListItemCollection 中。您可以尝试编写自己的集合,或从 ListItemCollection 继承,并覆盖 add、delete、insert 方法来调用您自己定义的事件,在被调用后。
    猜你喜欢
    • 2011-04-18
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多