[英]How can i add some properties to UserControl?
我有一個ListBox的UserControl:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Lightnings_Extractor
{
public partial class ListBoxControl : UserControl
{
private List<int> m_itemIndexes = new List<int>();
public ListBoxControl()
{
InitializeComponent();
this.listBox1.SelectedIndex = 0;
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
int index = listBox1.IndexFromPoint(e.X, e.Y);
listBox1.SelectedIndex = index;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
if (m_itemIndexes.Contains(index))
return;
m_itemIndexes.Add(index);
DrawItem(index);
}
else if (e.Button == MouseButtons.Left)
{
if (!m_itemIndexes.Contains(index))
return;
m_itemIndexes.Remove(index);
DrawItem(index);
}
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
bool coloring = m_itemIndexes.Contains(e.Index);
bool selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
if (coloring)
{
using (var brush = new SolidBrush(Color.Red))
{
e.Graphics.FillRectangle(brush, e.Bounds);
}
}
else
{
e.DrawBackground();
}
string item = listBox1.Items[e.Index].ToString();
e.Graphics.DrawString(item, e.Font, selected || coloring ? Brushes.White : Brushes.Black, e.Bounds, StringFormat.GenericDefault);
if (selected)
e.DrawFocusRectangle();
}
private void DrawItem(int index)
{
Rectangle rectItem = listBox1.GetItemRectangle(index);
listBox1.Invalidate(rectItem);
}
}
}
例如以下行:
using (var brush = new SolidBrush(Color.Red))
現在將其設置為紅色。 但是我希望用戶能夠在其代碼中的任何位置或以其他形式或類將其更改為任何顏色。 不僅在此UserControl代碼中。
我如何添加這樣的屬性?
只需像通常那樣聲明一個屬性:
[Browsable(true)] //so it appears in object explorer
public Color MyListColor
{
get { return m_MyListColor;}
set
{
m_MyListColor = value;
Refresh();//or Update
}
}
將屬性設置為新值后,它將調用Refresh()來重新繪制包括畫筆在內的控件。
只需添加一個新屬性。
public Brush Fill {get;set;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.