【发布时间】:2015-06-29 19:49:46
【问题描述】:
我有一个与Jinesh's 非常相似的问题。我需要在我的 ViewModel 代码中获取组合框的 SelectedIndex(或 SelectedItem 或 SelectedValue)的 值(即,当用户在组合框中选择一个项目时,我需要该索引(或项目或值)来更新 ViewModel 代码中的属性)。我遵循了Sheridan's answer 和Felix C's answer 中的建议,但是当所选项目更改时,我的属性没有得到更新。我正在尝试将新选择的索引值作为“更新”按钮代码的一部分。
查看:
<ComboBox Name="cboMonth"
ItemsSource="{Binding MonthsList, Mode=OneTime}"
DisplayMemberPath="month"
SelectedIndex="{Binding MonthIndex, Mode=TwoWay}"/>
<Button Name="btnUpdate"
Content="Update"
Command="{Binding processUpdateButton}" />
视图模型:
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));
}
当我的页面第一次呈现时,我的组合框默认为索引 5(6 月 6 日),而有问题的属性 _monthIndex 反映了 5。当我在组合框中选择一个新月份时(例如,10 月)然后单击我的更新按钮 (btnUpdate),_monthIndex 应该反映 9,但仍反映 5。为什么?感谢任何/所有帮助。谢谢。
【问题讨论】: