当存在重复条目时,为什么 WPF ComboBox 上的 SelectedIndex 不更新?
我使用 MVVM 模式将 ComboBox SelectedIndex 值绑定到视图模型中的 int:
<ComboBox ItemsSource="{Binding DropdownListChoices}" Margin="5,2,5,1" Width="320" Height="23"
Style="{StaticResource comboBoxWithErrorHandling}" SelectedIndex="{Binding SelectedComboBoxIndex}">
视图模型:
public class FieldViewModel : ObservableObject, IDataErrorInfo
{
private int _selectedComboBoxIndex;
public int SelectedComboBoxIndex
{
get { return _selectedComboBoxIndex; }
set
{
if (_selectedComboBoxIndex != value)
{
_selectedComboBoxIndex = value;
RaisePropertyChanged("SelectedComboBoxIndex");
}
}
}
// ...
}
在代码的不同部分中,我填充 DropdownListChoices。假设元素是 A、B、C、A、D。正确选择 B、C 或 D 会使 SelectedComboBoxIndex 获得预期值(分别为 1、2 或 4)。但是,无论选择第一个还是第二个 A,选择 A 都会将 SelectedComboBoxIndex 设置为 0。在选择第二个 A 时,我预计所选索引为 3。
为什么会发生这种情况?是否有不同的方法来实现我想要做的事情,即获取所选的绝对列表索引?
I am using the MVVM pattern to bind a ComboBox SelectedIndex value to an int in the view model:
<ComboBox ItemsSource="{Binding DropdownListChoices}" Margin="5,2,5,1" Width="320" Height="23"
Style="{StaticResource comboBoxWithErrorHandling}" SelectedIndex="{Binding SelectedComboBoxIndex}">
View model:
public class FieldViewModel : ObservableObject, IDataErrorInfo
{
private int _selectedComboBoxIndex;
public int SelectedComboBoxIndex
{
get { return _selectedComboBoxIndex; }
set
{
if (_selectedComboBoxIndex != value)
{
_selectedComboBoxIndex = value;
RaisePropertyChanged("SelectedComboBoxIndex");
}
}
}
// ...
}
In a different part of the code, I populate DropdownListChoices. Let's say the elements are for instance A, B, C, A, D. Selecting B, C or D correctly causes SelectedComboBoxIndex to get the expected value (1, 2 or 4, respectively). But selecting A will set SelectedComboBoxIndex to 0, regardless of whether the first or the second A was selected. On selecting the second A, I would expect the selected index to be 3.
Why does this happen? Is there a different way of achieving what I'm trying to do, namely to get the absolute list index which was selected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选择器控件中永远不应该有重复的项目,如果您将原始值包装在类中,它只会混淆它们并导致异常。
You should never have duplicate items in selector-controls, it will only confuse them and cause anomalies, if you have primitive values wrap them in a class.