2009-06-11 72 views
0

我有兩個ComboBox元素,一個用數據綁定,一個沒有。爲什麼我無法在數據綁定組合框上設置SelectedIndex?

在沒有我可以設置SelectedIndex罰款。

但是在數據綁定的那個,如果我設置SelectedIndex,它說,「AG_E_INVALID_ARGUMENT」。

但是,如果我將它設置爲ViewModel中的值(SelectedIndex =「{Binding SelectedCustomerIndex}」),那麼它會顯示「對象引用未設置爲對象的實例。

有誰知道我爲什麼不能在一個像這樣的數據綁定的組合框上設置SelectedIndex?

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> 

視圖模型:

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 

    } 
} 

回答

相關問題