有沒有辦法讓ListBox中的某些項目只讀/禁用,因此無法選擇它們?或者是否有任何類似ListBox的控件來提供這種功能?有隻讀/禁用項目的WinForms列表框
4
A
回答
3
ListBox不支持。你可以栓上一些東西,你可以取消選擇一個選定的項目。下面是防止偶數項被選中一個愚蠢的例子:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; ix--) {
if (listBox1.SelectedIndices[ix] % 2 != 0)
listBox1.SelectedIndices.Remove(listBox1.SelectedIndices[ix]);
}
}
但閃爍是相當明顯,它打亂了鍵盤導航。您可以通過使用CheckedListBox獲得更好的效果,可以防止用戶檢查框的項目:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
if (e.Index % 2 != 0) e.NewValue = CheckState.Unchecked;
}
但是現在你不能覆蓋圖紙,使它看起來明顯的是,該項目是不可選的用戶。這裏沒有很好的解決方案,只是不在盒子中顯示不應該選擇的項目就簡單多了。
1
@Hans解決方案導致短時間選擇物品ID,然後選擇消失。我不喜歡這樣 - 這可能會讓最終用戶感到困惑。
我寧願隱藏應禁用該項目的一些編輯選項按鈕:
if (lbSystemUsers.Items.Count > 0 && lbSystemUsers.SelectedIndices.Count > 0)
if (((RemoteSystemUserListEntity)lbSystemUsers.SelectedItem).Value == appLogin)
{
bSystemUsersDelete.Visible = false;
bSystemUsersEdit.Visible = false;
}
else
{
bSystemUsersDelete.Visible = true;
bSystemUsersEdit.Visible = true;
}
這裏列出了用戶和禁止以編輯到編輯面板實際登錄的用戶列表。
1
ListBox
沒有ReadOnly
(或類似)屬性,但可以自定義ListBox
控件。下面是一個工作非常適合我的解決方案:
https://ajeethtechnotes.blogspot.com/2009/02/readonly-listbox.html
public class ReadOnlyListBox : ListBox
{
private bool _readOnly = false;
public bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
protected override void DefWndProc(ref Message m)
{
// If ReadOnly is set to true, then block any messages
// to the selection area from the mouse or keyboard.
// Let all other messages pass through to the
// Windows default implementation of DefWndProc.
if (!_readOnly || ((m.Msg <= 0x0200 || m.Msg >= 0x020E)
&& (m.Msg <= 0x0100 || m.Msg >= 0x0109)
&& m.Msg != 0x2111
&& m.Msg != 0x87))
{
base.DefWndProc(ref m);
}
}
}
0
我知道這是舊線,但我會後對未來的其他讀者一種解決方法。
listBox.Enabled = false;
listBox.BackColor = Color.LightGray;
這會將列表框的背景顏色更改爲淺灰色。所以這不是內置的「本地方式」,但至少給了用戶一些反饋,他不應該/不能編輯該字段。
相關問題
- 1. C#Winforms列表框項目
- 2. GWT列表框 - 如何禁用列表框項目?
- 3. 在只讀列表框中刪除一個項目
- 4. 從列表框中讀取項目
- 5. Winforms列表框
- 6. 禁用列表框選擇只
- 7. 重新啓用列表框中禁用的項目
- 8. WinForms中的只讀組合框
- 9. Winforms中的禁用菜單項目仍顯示子項目
- 10. 使列表項只讀
- 11. 複選框列表只檢查有限的項目
- 12. asp.net列表框VS的WinForms列表框
- 13. 組合框項目連接到C#winforms中的列表格
- 14. 如何清除WinForms列表框中的焦點項目?
- 15. WPF在列表框的MouseMove上禁用項目選擇
- 16. 將列表框項轉移到另一個列表框(Winforms C#)
- 17. Winforms - 如何防止列表框項目選擇
- 18. 禁用或只讀 - 選擇框問題
- 19. 在ListView中禁用列表項目
- 20. 禁用和變灰列表項目
- 21. 禁用下拉列表項目
- 22. MVC4在選擇下拉列表項目時禁用文本框
- 23. 如何在列表框中禁用項目
- 24. 的WinForms列表框時listItems
- 25. 如何使用C#的WinForms獲得所選擇的項目ID列表框中
- 26. Sharepoint中列表項的只讀按鈕
- 27. 只有當字符串項目索引==列表項目索引
- 28. XAML列表框項目沒有亮點
- 29. 列表框中選擇所有項目
- 30. 有一個列表框項目模板
此鏈接可以幫助禁用checkedListBox中的項目使用C#Winform http://www.dotnettechy.com/problem-solutions/disabling-an-item-in-a-checkedlistbox-c-winform-10.aspx – 2012-01-31 15:08:16