0

正如主题所暗示的那样,我对 PropertyInfo.SetValue 有一些问题。言归正传,这是我的例子——我创建了自己的类,它的主要内容是演示对象:

using System;
using System.Reflection;

namespace TestingSetValue
{
public class Link
{
    private object presentationObject = null;
    private string captionInternal = string.Empty;

    public Link (string caption)
    {
        captionInternal = caption;
    }

    public string CaptionInternal
    {
        get { return captionInternal; }
        set { captionInternal = value; }
    }

    public bool Visible
    {
        get 
        {
            if (PresentationObject != null)
            {
                PropertyInfo pi = PresentationObject.GetType().GetProperty("Visible");

                if (pi != null)
                {
                    return Convert.ToBoolean(pi.GetValue(PresentationObject, null));
                }
            }

            return true;
        }

        set
        {
            if (PresentationObject != null)
            {
                PropertyInfo pi = PresentationObject.GetType().GetProperty("Visible");

                if (pi != null)
                {
                    pi.SetValue(PresentationObject, (bool)value, null);
                }
            }
        }
    }

    public object PresentationObject
    {
        get { return presentationObject; }
        set { presentationObject = value; }
    }

}

}

然后,我这样做:

private void btnShowLink_Click(object sender, EventArgs e)
    {
        Link link = new Link("Here I am!");

        this.contextMenu.Items.Clear();
        this.contextMenu.Items.Add(link.CaptionInternal);

        link.PresentationObject = this.contextMenu.Items[0];
        link.Visible = true;

        lblCurrentVisibility.Text = link.Visible.ToString();
    }

现在,我可以想象这看起来不太合乎逻辑/经济,但它显示了我真正问题的本质。即,在我调用后,为什么演示对象的可见性(以及 link.Visible 的值)没有改变:

link.Visible = true;

我根本不知道还能做些什么来完成这项工作......任何帮助都深表感谢。

为了让事情变得更有趣,属性 Enabled 的行为符合它的预期......

PropertyInfo pi = PresentationObject.GetType().GetProperty("Enabled");

是否与 Visible 实际上是 ToolStripDropDownItem 基础基础对象的属性,而 Enabled 是 ToolStripDropDownItem 的“直接”属性这一事实有关?

4

2 回答 2

1

检查http://msdn.microsoft.com/en-us/library/system.web.ui.control.visible.aspx。也许这会导致您的问题。

有一条非常重要的信息:

如果此属性为 false,则不呈现服务器控件。在组织页面布局时,您应该考虑到这一点。如果未呈现容器控件,则即使将单个控件的 Visible 属性设置为 true,也不会呈现它包含的任何控件。在这种情况下,即使您已将 Visible 属性显式设置为 true,单个控件也会返回 false。(也就是说,如果父控件的 Visible 属性设置为 false,则子控件继承该设置并且该设置优先于任何本地设置。)

于 2011-07-15T18:06:20.467 回答
1

如果您事先说这是什么类,那么弄清楚这一点会更容易,但现在我们知道它是 ToolStripDropDownItem,我们可以推断出它的意思是 WinForms。

您看到的是 ToolStripItem 的 Visible 属性的奇怪之处。它的 setter 和 getter 没有直接联系在一起。MSDN 说

“Available 属性与 Visible 属性的不同之处在于,Available 指示是否显示 ToolStripItem,而 Visible 指示是否显示 ToolStripItem 及其父项。将 Available 或 Visible 设置为 true 或 false 会将其他属性设置为 true 或 false。 "

换句话说,您想使用 Available 属性而不是 Visible 属性

于 2011-07-15T18:44:49.647 回答