2017-07-24 87 views
0

我有一個簡單的表單,它使用DataBinding綁定到一組對象。最初我不希望ComboBox顯示選擇,所以我將其選定索引設置爲-1。但是,當組合框變爲選中狀態時,我無法取消選擇它,而無需選取值。在SeclectedItem上綁定組合框無法更改選擇

如何在不選取值的情況下取消選擇ComboBox(選擇其他控件)?

要重新創建,創建一個新的winform,添加一個組合框和文本框,然後使用此代碼:當形式開始了ComboBox應選擇

Imports System.Collections.Generic 

Public Class Form1 

    Public Property f As Person 

    Public Sub New() 
     ' This call is required by the designer. 
     InitializeComponent() 

     ' Add any initialization after the InitializeComponent() call. 
     Dim db As New People 
     ' ComboBox1.CausesValidation = False 
     ComboBox1.DataSource = db 
     ComboBox1.DisplayMember = "Name" 
     ComboBox1.DataBindings.Add("SelectedItem", Me, "f", False, DataSourceUpdateMode.OnPropertyChanged) 
     ComboBox1.SelectedIndex = -1 
    End Sub 

End Class 

Public Class Person 
    Public Property Name As String 
End Class 

Public Class People 
    Inherits List(Of Person) 

    Public Sub New() 
     Me.Add(New Person With {.Name = "Dave"}) 
     Me.Add(New Person With {.Name = "Bob"}) 
     Me.Add(New Person With {.Name = "Steve"}) 
    End Sub 
End Class 

,這是無法選擇文本框。

我發現在ComboBox上切換CausesValidation爲False可以修復問題,但會中斷DataBinding。

+1

我認爲結合'ComboBox'(和更一般'ListControl')不能被取消選擇列表,因爲'CurrencyManager'不允許設置的'Position'爲-1時基礎列表'Count'是> 0 。 –

+0

解決方法添加無效值的NONE項目。 – Ramankingdom

+0

允許用戶選擇無效值不是一個好的解決方案 –

回答

1

找到了解決方案! (謝謝伊凡!)

如果ComboBox作爲-1的SelectedIndex,當它是Validating時會暫時禁用綁定。

 AddHandler ComboBox1.Validating, AddressOf DisableBindingWhenNothingSelected 
     AddHandler ComboBox1.Validated, AddressOf DisableBindingWhenNothingSelected 

    ''' <summary> 
    ''' Temporarily disables binding when nothing is selected. 
    ''' </summary> 
    ''' <param name="sender">Sender of the event.</param> 
    ''' <param name="e">Event arguments.</param> 
    ''' <remarks>A list bound ComboBox (and more generically ListControl) cannot be deselected, 
    ''' because CurrencyManager does not allow setting the Position to -1 when the underlying list Count is > 0. 
    ''' This should be bound to the Validating and Validated events of all ComboBoxes that have an initial SelectedIndex of -1.</remarks> 
    Protected Sub DisableBindingWhenNothingSelected(sender As Object, e As EventArgs) 
     Dim cb As ComboBox = DirectCast(sender, ComboBox) 
     If cb.SelectedIndex = -1 Then 
      If (cb.DataBindings.Count = 0) Then Exit Sub 
      If cb.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.Never Then 
       cb.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged 
      Else 
       cb.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.Never 
      End If 
     End If 
    End Sub 
相關問題