有沒有辦法讓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. 禁用列表框項目
- 3. winforms列表框項目到業務層
- 4. GWT列表框 - 如何禁用列表框項目?
- 5. 禁用/只讀取datagrid中一列中的所有組合框
- 6. 在只讀列表框中刪除一個項目
- 7. Winforms列表框
- 8. 從列表框中讀取項目
- 9. WinForms中的只讀組合框
- 10. Winforms中的禁用菜單項目仍顯示子項目
- 11. 禁用列表框選擇只
- 12. 將通用列表項添加到Winforms的列表框c#
- 13. 重新啓用列表框中禁用的項目
- 14. asp.net列表框VS的WinForms列表框
- 15. 限制在WinForms列表框中的項目數
- 16. 如何清除WinForms列表框中的焦點項目?
- 17. 組合框項目連接到C#winforms中的列表格
- 18. 使列表項只讀
- 19. 複選框列表只檢查有限的項目
- 20. 禁用列表視圖中的項目
- 21. 使用jquery啓用或禁用複選框列表項目
- 22. 禁用列表框中的選定項目VB6
- 23. PowerShell System.Windows.Forms禁用列表框中的某些項目
- 24. 關於選擇列表框中的項目禁用按鈕
- 25. 禁用選定列表視圖項目的藍色邊框
- 26. WPF在列表框的MouseMove上禁用項目選擇
- 27. 禁用Windows Phone 7中的列表框項目?
- 28. 將列表框項轉移到另一個列表框(Winforms C#)
- 29. WPF。禁用/啓用列表框項目ContextMenu和MVVM
- 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