トピックが示唆しているように、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 の「直接」プロパティであるという事実に関連している可能性がありますか?