为什么我不能在数据绑定的ComboBox上设置SelectedIndex?

时间:2009-06-11 01:06:50

标签: silverlight data-binding xaml combobox

我有两个ComboBox元素,一个是数据绑定,另一个是没有。

在没有的情况下我可以设置SelectedIndex。

但是在数据绑定的那个上,如果我设置了SelectedIndex,它会说“ AG_E_INVALID_ARGUMENT ”。

但是如果我将它设置为ViewModel中的值(SelectedIndex =“{Binding SelectedCustomerIndex}”),则表示“对象引用未设置为对象的实例。”

有谁知道为什么我不能在这样的数据绑定的ComboBox上设置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

    }
}

1 个答案:

答案 0 :(得分:0)

SelectedItem真的很喜欢two-way bound