расширенный treenode / treeview, почти там, но - PullRequest
0 голосов
/ 22 декабря 2010

Я пишу расширенное древовидное представление, просто с несколькими дополнительными свойствами в моем классе TreeNode с поддержкой времени разработки.

Код полностью готов, но на данный момент я полностью застрял в следующем коде.Все, что я пытаюсь на этом этапе, приводит к (другому) исключению ...

Может быть, у кого-нибудь есть идеи, как идти дальше?Я больше не знаю

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Drawing.Design;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Windows.Forms;</p>

<p>namespace MyProject.Forms
{
    public class MenuTreeView : TreeView
    {
        public MenuTreeView()
        {
            //
        }</p>

<code>    [Editor(typeof(MenuTreeNodeCollectionEditor), typeof(UITypeEditor))]
    //[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public new TreeNodeCollection Nodes
    {
        get
        {
            return base.Nodes;
        }
    }
}

[Serializable]
[DefaultProperty("Text")]
[TypeConverter(typeof(MenuTreeNodeConverter))]
public class MenuTreeNode : TreeNode, ISerializable
{
    private string description = "";

    public MenuTreeNode()
        : base()
    {
        //
    }

    public MenuTreeNode(string text)
        : base(text)
    {
        //
    }

    public MenuTreeNode(string text, string description)
        : base(text)
    {
        this.description = description;
    }

    public MenuTreeNode(string text, MenuTreeNode[] children)
        : base(text, children)
    {
        //
    }

    public override object Clone()
    {
        object clone = base.Clone();
        MenuTreeNode node = clone as MenuTreeNode;
        if (node != null)
        {
            node.Description = Description;
            return node;
        }
        else return clone;
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        Serialize(info, context);
    }

    protected override void Deserialize(SerializationInfo info, StreamingContext context)
    {
        Description = info.GetString("Description");

        base.Deserialize(info, context);
    }

    protected override void Serialize(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Description", Description);

        base.Serialize(info, context);
    }

    [DefaultValue("")]
    public string Description
    {
        get { return description; }
        set { description = value; }
    }
}

public class MenuTreeNodeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type type)
    {
        if (type == typeof(string))
        {
            return true;
        }

        return base.CanConvertFrom(context, type);
    }

    public override bool CanConvertTo(ITypeDescriptorContext context, Type type)
    {
        if (type == typeof(InstanceDescriptor) || type == typeof(string))
        {
            return true;
        }

        return base.CanConvertTo(context, type);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo info, object value)
    {
        if (value != null && value is string)
        {
            string[] items = ((string)value).Split(',');
            return new MenuTreeNode(items[0], items[1]);
        }

        return base.ConvertFrom(context, info, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo info, object value, Type type)
    {
        MenuTreeNode node = value as MenuTreeNode;
        if (value != null)
        {
            if (type == typeof(string))
            {
                return node.Text + "," + node.Description;
            }
            else if (type == typeof(InstanceDescriptor))
            {
                ConstructorInfo constructor = typeof(MenuTreeNode).GetConstructor(new Type[] { typeof(string), typeof(string) });
                return new InstanceDescriptor(constructor, new object[] { node.Text, node.Description }, true);
            }
        }

        return base.ConvertTo(context, info, value, type);
    }
}

public class MenuTreeNodeCollectionEditor : CollectionEditor
{
    public MenuTreeNodeCollectionEditor(Type t)
        : base(t)
    {
        //
    }

    protected override Type CreateCollectionItemType()
    {
        return typeof(MenuTreeNode);
    }

    protected override Type[] CreateNewItemTypes()
    {
        return new Type[] { typeof(MenuTreeNode) };
    }

    protected override object CreateInstance(Type itemType)
    {
        if (itemType == typeof(MenuTreeNode))
        {
            return new MenuTreeNode();
        }

        return base.CreateInstance(itemType);
    }

    protected override string GetDisplayText(object value)
    {
        MenuTreeNode node = value as MenuTreeNode;
        if (node != null)
        {
            return "MenuTreeNode: " + node.Text;
        }

        return base.GetDisplayText(value);
    }
}
</code>

}

[править] После перемещения Treeview в другой проект все идет хорошо.Не спрашивайте меня, почему ...

Но: сохраняются только свойства Text и Description, поскольку конструктор не создает локальные переменные для каждого добавляемого узла.Как мне этого добиться?

[править] Наконец-то, я получил его на работу!благодаря этому: http://netcode.ru/dotnet/?lang=&katID=30&skatID=283&artID=7827

Решением было удаление typeof (string) из TypeConvertor, а когда типом является InstanceDescriptor, просто вернуть конструктор по умолчанию.

1 Ответ

0 голосов
/ 23 декабря 2010

Наконец-то я получил его на работу! благодаря этой статье: http://netcode.ru/dotnet/?lang=&katID=30&skatID=283&artID=7827

Решением было удаление typeof (string) из TypeConvertor, а когда типом является InstanceDescriptor, то просто возвращает конструктор по умолчанию.

...