コンポーネント トレイで編集中に名前を変更できるようにしたいコンポーネントを作成しました。name プロパティの Designer アクションを追加しましたが、行き詰まりました。
プロパティ グリッドを見ると、name プロパティが括弧で囲まれていることがわかります。これは、通常のプロパティではないことを示しています。
これは可能ですか?
コンポーネント トレイで編集中に名前を変更できるようにしたいコンポーネントを作成しました。name プロパティの Designer アクションを追加しましたが、行き詰まりました。
プロパティ グリッドを見ると、name プロパティが括弧で囲まれていることがわかります。これは、通常のプロパティではないことを示しています。
これは可能ですか?
Component
を使用して設計時にの名前を変更できますComponent.Site.Name
。名前が重複している場合に例外を処理するには、コードを try/catch ブロックに配置する必要があります。
コード:
コンポーネントのデザイナーを実装する場合、デザイン時にコンポーネントの名前を変更するためのマン コードは次のとおりです。
this.Component.Site.Name = "SomeName";
コンポーネントとコンポーネント デザイナーの完全な実装を次に示します。コンポーネント デザイナーには、コンポーネントを右クリックするとアクセスできる動詞があり、コマンド トレイのプロパティ グリッドからもアクセスできます。コマンドをクリックするとRename
、コンポーネントの名前が に設定されSomeName
ます。また、同じ名前のコンポーネントがある場合は、エラー メッセージが表示されます。より現実的なサンプルでは、オーバーライドActionLists
して、ユーザーが新しい名前自体を入力できるようにすることができます。
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
[Designer(typeof(MyComponentDesigner))]
public class MyComponent : Component
{
public string SomeProperty { get; set; }
}
public class MyComponentDesigner : ComponentDesigner
{
DesignerVerbCollection verbs;
public MyComponentDesigner() : base() { }
public override DesignerVerbCollection Verbs
{
get
{
if (verbs == null)
{
verbs = new DesignerVerbCollection();
verbs.Add(new DesignerVerb("Rename", (s, e) =>
{
try
{
this.Component.Site.Name = "SomeName";
this.RaiseComponentChanged(null, null, null);
}
catch (Exception ex)
{
var svc = ((IUIService)this.GetService(typeof(IUIService)));
svc.ShowError(ex);
}
}));
}
return verbs;
}
}
}
一部のプロパティはデザイン環境で特別であり、実際に設定できるのはタイプ記述子を介してのみです。これは名前の場合に当てはまるかもしれませんが、Visible、Locked、Enabledなどの場合には確かに当てはまります。おそらく、これはあなたに今のところ見るべき何かを与えるでしょう。
SetHiddenValue(control, "Visible", false);
SetHiddenValue(control, "Locked", true);
SetHiddenValue(control, "Enabled", false);
/// <summary>
/// Sets the hidden value - these are held in the type descriptor properties.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="name">The name.</param>
/// <param name="val">The val.</param>
private static void SetHiddenValue(Control control, string name, object val)
{
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(control)[name];
if (descriptor != null)
{
descriptor.SetValue(control, val);
}
}