不明白这种情况。请帮助,
当我第一次加载窗口时,Combobox显示验证错误,并在绑定时显示消息“值''无法转换”“SelectedValue =”{绑定ID,ElementName = mySelf,Mode = TwoWay}“......通过调用UpdateTarget(),验证错误就消失了。在这两种情况下,ID都是0,绑定到SelectedValue属性(Load和ButtonClick)
我看到的唯一区别是在InitializeComponents之后加载了Employees集合(如果我在InitializeComponents验证错误消失之前添加了它)
public class Employee
{
public Employee(Int32 id, String name)
{
this.ID = id;
this.Name = name;
}
public int ID { get; set; }
public string Name { get; set; }
}
XAML
<Grid>
<ComboBox VerticalAlignment="Center" Margin="12,57,424,93" x:Name="cmbEntityBuyer2" Width="230"
ItemsSource="{Binding Employees, ElementName=mySelf}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValue="{Binding ID, ElementName=mySelf, Mode=TwoWay}"
IsEditable="False"/>
<TextBox Text="{Binding ElementName=cmbEntityBuyer2,Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Height="25" Margin="12,12,424,134" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,108,0,0" Name="button1" VerticalAlignment="Top" Width="230" Click="button1_Click" />
</Grid>
背后的代码
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
Employees.Add(new Employee(1, "Vinay"));
Employees.Add(new Employee(2, "Leny"));
}
Int32 _id = 0;
public Int32 ID
{
get { return _id; }
set { _id = value; OnPropertyChanged("ID"); }
}
ObservableCollection<Employee> _emp = new ObservableCollection<Employee>();
public ObservableCollection<Employee> Employees
{
get { return _emp; }
set { _emp = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
private void button1_Click(object sender, RoutedEventArgs e)
{
String error = Validation.GetErrors(cmbEntityBuyer2)[0].ErrorContent.ToString();
cmbEntityBuyer2.GetBindingExpression(ComboBox.SelectedValueProperty).UpdateTarget();
}
}