enter code here
鉴于此例:
Public Enum Gender
Masculine
Femenine
End Enum
public class ViewModel
private _gender as Gender
Public Property Gender() As Gender
Get
Return _gender
End Get
Set(ByVal value As Gender)
_gender = value
End Set
End Property
end class
Private Sub Form_Load
cmbGender.DataSource = [Enum].GetValues(GetType(Enums.Sexo)) //combobox shows gender ok
cmbGender.DataBindings.Add(New Binding("SelectedItem",ViewModel , "Gender", False, DataSourceUpdateMode.OnPropertyChanged))
end sub
Combobox
使用ViewModel
getter在SelectedItem
执行后立即设置Databindings.Add
但在用户界面中SelectedItem
更改时从不使用setter。
我做错了什么?
修改
感谢Sriram Sakthivel启发并检查组合框事件。最后的情况是:
当SelectedItem
加注时,使用DataSourceUpdateMode.OnValidation
,combobox.causesValidation = true
和LostFocus
有效。如果您需要onPropertyChanged
,请使用SelectedIndex
和下面的Sriram Sakthivel代码。
答案 0 :(得分:1)
它会在LostFocus
ComboBox
事件中更新,因为SelectedItem
不会提出更改通知(这是立即更新所必需的)。
作为一种变通方法,您可以使用SelectedIndex
属性,该属性通过SelectedIndexChanged
事件发布更改通知。但是有一个问题,SelectedIndex
类型为Int32
,您需要将其转换为Gender
,反之亦然。
以下是您将如何做到这一点:C#版
private void SetupBinding()
{
var binding = new Binding("SelectedIndex", model, "Gender", true, DataSourceUpdateMode.OnPropertyChanged);
binding.Format += binding_Format;
binding.Parse += binding_Parse;
comboBox1.DataBindings.Add(binding);
}
void binding_Parse(object sender, ConvertEventArgs e)
{
if (e.DesiredType == typeof(Gender))
{
e.Value = comboBox1.Items[(int)e.Value];
}
}
void binding_Format(object sender, ConvertEventArgs e)
{
if (e.DesiredType == typeof(int))
{
e.Value = comboBox1.Items.IndexOf(e.Value);
}
}
Vb.net很穷。所以我使用code converter将其从c#转换为vb.net。
Private Sub SetupBinding()
Dim binding = New Binding("SelectedIndex", model, "Gender", True, DataSourceUpdateMode.OnPropertyChanged)
AddHandler binding.Format, AddressOf binding_Format
AddHandler binding.Parse, AddressOf binding_Parse
comboBox1.DataBindings.Add(binding)
End Sub
Private Sub binding_Parse(sender As Object, e As ConvertEventArgs)
If e.DesiredType = GetType(Gender) Then
e.Value = comboBox1.Items(CInt(e.Value))
End If
End Sub
Private Sub binding_Format(sender As Object, e As ConvertEventArgs)
If e.DesiredType = GetType(Integer) Then
e.Value = comboBox1.Items.IndexOf(e.Value)
End If
End Sub