WPF/MVVM: SelectedIndex Binding Property not updat

2019-03-03 11:17发布

问题:

I've got a very similar question to Jinesh's. I need to get the value of the SelectedIndex (or SelectedItem or SelectedValue) of a combo box in to my ViewModel code (i.e., when a user selects an item in the combo box, I need that index (or item or value) to update a property in the ViewModel code). I've followed the suggestions in Sheridan's answer and Felix C's answer but my property is not getting updated when the selected item changes. I'm trying to get the newly selected index value as part of my "Update" button code.

View:

<ComboBox Name="cboMonth"
          ItemsSource="{Binding MonthsList, Mode=OneTime}"
          DisplayMemberPath="month"
          SelectedIndex="{Binding MonthIndex, Mode=TwoWay}"/>

<Button Name="btnUpdate"
        Content="Update"
        Command="{Binding processUpdateButton}" />

ViewModel:

public ObservableCollection<Month> MonthsList { get; set; }
private int _monthIndex;

public int MonthIndex
{
    get
    {                
        DateTime today = DateTime.Today;
        _monthIndex = today.Month - 1;
        return _monthIndex;
    }
    set
    {
        if (_monthIndex != value)
        {
            _monthIndex = value;
            RaisePropertyChanged("MonthIndex");
        }
    }
} 

public ICommand processUpdateButton
{
    get
    {
        if (_setUpdateButton == null)
        {
            _setUpdateButton = new RelayCommand(param => validateOdometer());
        }
            return _setUpdateButton;
        }            
    }

public void validateOdometer()
{
    Console.WriteLine("Validating odometer...");
    Console.WriteLine("Month Index: " + (_monthIndex));        
}

When my page first renders, I have the combo box defaulting to index 5 (06-June) and the property in question, _monthIndex, reflects 5. When I select a new month in the combo box (e.g., October) then click my update button (btnUpdate), _monthIndex should reflect 9 but it still reflects 5. Why? Appreciate any/all help. Thanks.

回答1:

The property getter ignores the previously set value and always returns the index of the current month.

The declaration should look like this:

private int monthIndex = DateTime.Today.Month - 1;

public int MonthIndex
{
    get { return monthIndex; }
    set
    {
        if (monthIndex != value)
        {
            monthIndex = value;
            RaisePropertyChanged("MonthIndex");
        }
    }
} 


标签: wpf mvvm