2009-06-11 12 views
0

Ich habe zwei ComboBox-Elemente, eines mit Datenbindung und eines ohne.Warum kann ich SelectedIndex nicht für eine datengebundene ComboBox festlegen?

Auf der einen ohne kann ich die SelectedIndex fein einstellen.

Aber auf der einen, die datengebunden ist, wenn ich den SelectedIndex, heißt es, "AG_E_INVALID_ARGUMENT".

Aber wenn ich es auf einen Wert im Ansichtsmodell gesetzt (SelectedIndex = „{Binding SelectedCustomerIndex}“), dann heißt es „Objektverweis nicht auf eine Instanz eines Objekts festgelegt.“

Weiß jemand, warum ich nicht einfach einen SelectedIndex auf einer ComboBox setzen kann, die so gebunden ist?

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> 

Ansichtsmodell:

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 

    } 
} 

Antwort

Verwandte Themen