Reputation: 767
When I load the window for the first time, Combobox shows validation error with message "Value '' could not be converted" on binding SelectedValue="{Binding ID, ElementName=mySelf, Mode=TwoWay}
... with call to UpdateTarget()
the validation error goes away. In both the cases ID is 0 which is bound to SelectedValue property (Load and ButtonClick)
Only difference which I see is Employees collection is loaded after InitializeComponents (which If I added before InitializeComponents validation error goes away)
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>
Code Behind
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();
}
}
Upvotes: 3
Views: 6809