I have two ComboBox elements, one with databinding and one without.
On the one without I can set the SelectedIndex fine.
But on the one that is databound, if I set the SelectedIndex, it says, "AG_E_INVALID_ARGUMENT".
But if I set it to a value in the ViewModel (SelectedIndex="{Binding SelectedCustomerIndex}") then it says "Object reference not set to an instance of an object."
Does anyone know why I can't just set a SelectedIndex on a ComboBox that is data bound like this?
XAML:
<Grid>
<StackPanel>
<Border CornerRadius="5" Background="#eee" >
<StackPanel HorizontalAlignment="Left" VerticalAlignment="top" Width="250">
<ComboBox ItemsSource="{Binding Customers}" SelectedIndex="0"
ItemTemplate="{StaticResource DataTemplateCustomers}"/>
</StackPanel>
</Border>
<ComboBox x:Name="WhichNumber" Width="100" HorizontalAlignment="Left" Margin="10" SelectedIndex="0">
<ComboBoxItem Content="One"/>
<ComboBoxItem Content="Two"/>
<ComboBoxItem Content="Three"/>
</ComboBox>
</StackPanel>
</Grid>
ViewModel:
using System.Collections.ObjectModel;
using System.ComponentModel;
using TestBasics737.Models;
namespace TestBasics737.ViewModels
{
public class PageViewModel : INotifyPropertyChanged
{
public PageViewModel()
{
Customers.Add(new Customer { FirstName = "Jim", LastName = "Smith" });
Customers.Add(new Customer { FirstName = "Angie", LastName = "Smithton" });
SelectedCustomerIndex = 0;
}
#region ViewModelProperty: SelectedCustomerIndex
private int _selectedCustomerIndex = 0;
public int SelectedCustomerIndex
{
get
{
return _selectedCustomerIndex;
}
set
{
_selectedCustomerIndex = value;
OnPropertyChanged("SelectedCustomerIndex");
}
}
#endregion
#region ViewModelProperty: Customers
private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers
{
get
{
return _customers;
}
set
{
_customers = value;
OnPropertyChanged("Customers");
}
}
#endregion
#region PropertChanged Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}