質問

I have some custom TreenodeTypes I want to fill with custom values. They look like this:

public class QuestionNode : TreeNode
{
    public string Question { get; set; }
    public new string Text
    {
        get { return string.Format("Question: {0}", Question); }
    }
}

When I add this Node to a treeview "trvWhatever":

trvWhatever.Nodes.Add(new QuestionNode { Question="WTF?"});

the Node is still invisible. The Treeview has the Node included, but the "Text"-Property is still null.

I understand that the base-Property is used instead of "my" property. Is there a way to change that?

役に立ちましたか?

解決

I understand that the base-Property is used instead of "my" property. Is there a way to change that?

Well not really. The problem is that it's not a virtual property, and you've just introduced a new property with the same name - it's not being called polymorphically.

Surely the simpler solution is just to set the Text property yourself... potentially within the constructor:

public class QuestionNode : TreeNode
{
    private readonly string question;

    public QuestionNode(string question)
    {
        this.question = question;
        this.Text = string.Format("Question: {0}", question);
    }
}

You could do this within the property setter instead, of course:

public class QuestionNode : TreeNode
{
    private string question;

    public string Question
    {
        get { return question; } 
        set
        {
            this.question = value;
            this.Text = string.Format("Question: {0}", question);
        }
    }
}

... but personally I'd stick to the constructor version myself, unless you have some reason you need to change the question later.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top