當我點擊列表框中的未選定項目時,它將被選中。客戶希望如果再次點擊(所以不使用cntrl鍵)它會取消選擇。C#listbox選擇並取消選擇MultiExtended模式下的項目
但我嘗試了很多東西,但沒有任何工作。所以這是可能的,如果可能的話可以有人解釋我如何使用一些C#代碼?
當我點擊列表框中的未選定項目時,它將被選中。客戶希望如果再次點擊(所以不使用cntrl鍵)它會取消選擇。C#listbox選擇並取消選擇MultiExtended模式下的項目
但我嘗試了很多東西,但沒有任何工作。所以這是可能的,如果可能的話可以有人解釋我如何使用一些C#代碼?
這將取消選擇所有/特定ListBox中的項目當你點擊列表框的空白區域。
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
int totalHeight = listBox1.ItemHeight * listBox1.Items.Count;
if(e.Y < totalHeight && e.Y >= 0)
{
// Item is Selected which user clicked.
if(listBox1.SelectedIndex == 0 && listBox1.SelectedItem != null) // Check if Selected Item is NOT NULL.
{
MessageBox.Show("Selected Index : " + listBox1.SelectedItem.ToString().Trim());
}
else
{
listBox1.SelectedIndex = -1;
MessageBox.Show("Selected Index : No Items Found");
}
}
else
{
// All items are Unselected.
listBox1.SelectedIndex = -1;
MessageBox.Show("Selected Index : " + listBox1.SelectedItem); // Do NOT use 'listBox1.SelectedItem.ToString().Trim()' here.
}
}
,你也可以改變你想要在選擇項目/未選擇做什麼的代碼。
如果選定的索引與精選的索引相同(將其保存在某處),則可以在所選索引事件中添加一些內容,然後將所選索引設置爲-1,因此不會選擇任何內容。
有沒有簡單的方法來做到這一點與內置選項。我的解決方案是當鼠標懸停在Control上時以編程方式發送一個虛擬Ctrl鍵(因此用戶不需要按或考慮任何事情)。如果您不需要MultiExtended
的附加功能,請嘗試使用MultiSimple
(MSDN)。
如果你這樣做,這裏的醜陋的解決方案:
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public const byte KEYEVENTF_KEYUP = 0x02;
public const int VK_CONTROL = 0x11;
private void listBox1_MouseEnter(object sender, EventArgs e)
{
keybd_event(VK_CONTROL, (byte)0, 0, 0);
}
private void listBox1_MouseLeave(object sender, EventArgs e)
{
keybd_event(VK_CONTROL, (byte)0, KEYEVENTF_KEYUP, 0);
}
從我的回答here。
@NominSim你不需要按Ctrl鍵。虛擬按鍵以編程方式執行。 – 2012-07-25 12:51:23
哦,我現在看到了,你說的很醜,但無論如何+1。 – NominSim 2012-07-25 12:52:11
這個答案值得兩個upvotes。那麼,你已經回答了兩次,所以你得到兩個upvotes! – 2013-02-18 11:37:11
堅持以SelectedValueChanged
事件並添加此:
string selected = null;
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
ListBox lb = sender as ListBox;
if (lb == null) { return; }
if (lb.SelectedItem != null && lb.SelectedItem.ToString() == selected)
{
selected = lb.SelectedItem.ToString();
lb.SetSelected(lb.SelectedIndex, false);
}
else
{
selected = lb.SelectedItem == null ? null : lb.SelectedItem.ToString();
}
}
這是一個Windows應用程序或ASP.Net應用程序? – PCasagrande 2012-07-25 12:44:12
你有沒有考慮使用MultiSimple模式? http://stackoverflow.com/questions/11350514/winforms-listbox-append-selection/11350601#11350601 – 2012-07-25 12:45:05
我沒有使用MultiSimple,因爲我認爲這沒有我想要的行爲(是的,很簡單)但這是正是我想要的thnx。 – Remco 2012-07-25 12:52:24