[英]C# Attach Property Control base class
我想知道如何將一個用戶控件中的屬性添加到基本控件屬性列表中。 這可能嗎?
So what I am doing is this:
private static List<LabelType> ConvertControlCollectionToList(Control customContainer)
{
LabelTypeList.LabelProps.Clear();
foreach (Control c in customContainer.Controls)
{
LabelTypeList.LabelProps.Add(new LabelType());
LabelTypeList.LabelProps.Last().Name = c.Name;
LabelTypeList.LabelProps.Last().Top = c.Top;
LabelTypeList.LabelProps.Last().Left = c.Left;
LabelTypeList.LabelProps.Last().Height = c.Height;
LabelTypeList.LabelProps.Last().Width = c.Width;
LabelTypeList.LabelProps.Last().Font = c.Font;
LabelTypeList.LabelProps.Last().Text = c.Text;
LabelTypeList.LabelProps.Last().DataColumn = c.?????
LabelTypeList.LabelProps.Last().Rotation = c.?????
}
return LabelTypeList.LabelProps;
}
我在列表的末尾有兩個屬性,這些屬性是我的用戶控件自定義的,但是我需要將它們添加到基本控件類中,因此當我將集合加載回表單時,可以訪問DataColumn和Rotation的設置。 那有意義嗎?
謝謝。
例如,假設您的控件是一個名為txtFirstName
的TextBox
並且您需要一個屬性來表示UserControl
上該TextBox
的文本:
public string FirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
編輯
鑒於問題的編輯,不,您不能完全按照自己的要求進行操作(將屬性添加到基類的屬性中)。 但是,您可以檢查特定控件是否是UserControl
的實例,如果是,則可以收集這些屬性。 為此,請使用以下命令:
private static List<LabelType> ConvertControlCollectionToList(Control customContainer)
{
LabelTypeList.LabelProps.Clear();
foreach (Control c in customContainer.Controls)
{
LabelType lt = new LabelType();
LabelTypeList.LabelProps.Add(lt);
lt.Name = c.Name;
lt.Top = c.Top;
lt.Left = c.Left;
lt.Height = c.Height;
lt.Width = c.Width;
lt.Font = c.Font;
lt.Text = c.Text;
YourUserControlType uc = c as YourUserControlType;
if(uc != null)
{
lt.DataColumn = uc.DataColumn;
lt.Rotation = uc.Rotation;
}
}
return LabelTypeList.LabelProps;
}
(我刪除了對Last()
的調用,因為這是LINQ擴展方法,並且每次設置屬性時都會遍歷整個列表)。
在WPF中,可以使用“ 附加屬性”來提供此行為。 這就是Grid.Row之類的工作方式。
在Windows窗體中,您將需要使用Extender Provider 。
請注意,這兩個選項都不會將屬性真正添加到基類中-您不能在子類中更改基類的結構。 它們確實添加了設計時可用的控件可用的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.