我爲你提供了一些建議。在我的迴應的底部,我包含了能夠證明我的建議的代碼。
建議1:在你的UC鼠標點擊固定
當您註冊一個用戶控件(UC)的鼠標點擊事件你這樣做的用戶控件本身,而不是爲你放置在用戶控件,如任何控件您的標籤等。如果您點擊其中一個子控件,則點擊將不會被底層UC所「看到」。
要解決此問題,請爲您的所有子控件註冊MouseClick事件;您甚至可以爲UserControl本身註冊相同的MouseClick事件處理程序。
建議2:設置你的UC的邊框
我將你的代碼設置UC的BorderStyle
到UC本身。創建公共屬性IsSelected
,在選擇UC時設置爲true。在財產的設置者更新加州大學的BorderStyle
屬性取決於財產的價值。
爲您的UC公開一個IsSelected
屬性可能很方便:您可以查詢一組這些UC來查看哪些是被選中的,而不是像通過Form-level變量那樣嘗試跟蹤控件之外的這種狀態。
編輯迴應您的評論:
這裏有一個如何查詢一個FlowLayoutPanel中的UCS,看看是否有任何選擇的一個例子,如果發現你怎麼可能採取一些行動。在這種情況下,動作是調用EditUser
方法,它的參數值,你從選定UC性能得到:
var selectedUC = flowLayoutPanel.Controls.Cast<UserControl1>().FirstOrDefault(uc => uc.IsSelected);
if (selectedUC != null) {
// Use the properties of the UC found to be selected as parameters is method EditUser.
EditUser(selectedUC.Name, selectedUC.Username, selectedUC.Administrator);
}
建議3:一組你的UCS的管理選擇
如果你想要取消選擇用戶點擊(即選擇)組中的所有UC,則需要在UC中創建一個點擊UC時觸發的事件。此事件的處理程序明確地將IsSelected
設置爲對於集合中的所有UC(例如在諸如Form,FlowLayoutPanel等的容器類型控制中)的假,則被點擊的UC中的MouseClick處理器然後將設置單擊的UC的IsSelected
爲真。
值得考慮創建另一個管理一組UCs的UserControl類型。這個新的UserControl可以封裝你的UC的創建和狀態管理的代碼,並且會促進在其他項目中使用你的UCs,並且讓託管你的UCs的表單更加清潔。
我想,而不是包括一系列脫節的代碼片段,我的每個建議,我想包括我希望是什麼的代碼,讓你重現什麼我談論的最低金額。
創建一個新的Visual Studio的Winform項目,並使用Form1
類以下內容:
public partial class Form1 : Form
{
public Form1() {
InitializeComponent();
flowLayoutPanel = new FlowLayoutPanel {
Dock = DockStyle.Fill,
};
this.Controls.Add(flowLayoutPanel);
// Add several sample UCs.
for (int i = 0; i < 10; i++) {
var uc = new UserControl1();
uc.WasClicked += UsersGrid_WasClicked;
flowLayoutPanel.Controls.Add(uc);
}
}
FlowLayoutPanel flowLayoutPanel;
// Event handler for when MouseClick is raised in a UserControl.
void UsersGrid_WasClicked(object sender, EventArgs e) {
// Set IsSelected for all UCs in the FlowLayoutPanel to false.
foreach (Control c in flowLayoutPanel.Controls) {
if (c is UserControl1) {
((UserControl1)c).IsSelected = false;
}
}
}
}
下一個用戶控件添加到項目中。保留名稱UserControl1
並添加一對標籤和一個PictureBox。使用此代碼UserControl1
類:
public partial class UserControl1 : UserControl
{
public UserControl1() {
InitializeComponent();
this.Load += UsersGrid_Load;
}
// Event fires when the MouseClick event fires for the UC or any of its child controls.
public event EventHandler<EventArgs> WasClicked;
private void UsersGrid_Load(object sender, EventArgs e) {
// Register the MouseClick event with the UC's surface.
this.MouseClick += Control_MouseClick;
// Register MouseClick with all child controls.
foreach (Control control in Controls) {
control.MouseClick += Control_MouseClick;
}
}
private void Control_MouseClick(object sender, MouseEventArgs e) {
var wasClicked = WasClicked;
if (wasClicked != null) {
WasClicked(this, EventArgs.Empty);
}
// Select this UC on click.
IsSelected = true;
}
private bool _isSelected;
public bool IsSelected {
get { return _isSelected; }
set {
_isSelected = value;
this.BorderStyle = IsSelected ? BorderStyle.Fixed3D : BorderStyle.None;
}
}
}
我猜UsersGrid是你的用戶控件? –
@JustinSkiles - 是的。對不起,我應該解釋一下。 – hshah