WPF - 绑定到 ItemsSource 和 SelectedIndex 会引发异常吗?
这段代码给了我一个“参数超出范围”的异常。当我删除对 SelectedIndex
的绑定时,ComboBox
填充得很好,并且不会引发异常。
知道我做错了什么吗?这(由于某种原因)不可能吗?
代码:
public class RuleMap<T> : INotifyPropertyChanged
{
public ObservableCollection<string> Options
{
get
{
return new ObservableCollection(){"A", "B", "C"};
}
}
public int SelectedIndex
{
get
{
return 0;
}
}
}
public ObservableCollection<RuleMap> FilterItemSource;
XAML:
<ItemsControl ItemsSource="{Binding FilterItemSource}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"> <ComboBox Width="150" SelectedIndex="{Binding SelectedIndex}"
ItemsSource="{Binding Options}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
This code gives me an “Argument out of range” exception. When I remove the binding to the SelectedIndex
, the ComboBox
is populated just fine and no exception is thrown.
Any idea what I am doing wrong? Is this (for some reason) not possible?
Code:
public class RuleMap<T> : INotifyPropertyChanged
{
public ObservableCollection<string> Options
{
get
{
return new ObservableCollection(){"A", "B", "C"};
}
}
public int SelectedIndex
{
get
{
return 0;
}
}
}
public ObservableCollection<RuleMap> FilterItemSource;
XAML:
<ItemsControl ItemsSource="{Binding FilterItemSource}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"> <ComboBox Width="150" SelectedIndex="{Binding SelectedIndex}"
ItemsSource="{Binding Options}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我猜
SelectedIndex
它是一个只读属性。其他问题可能是 0 不在集合中
I guess that
SelectedIndex
it is a ReadOnly Property.Other problem can be that 0 it's not in the collection
我认为在 selectedIndex 绑定之前不会添加项目,并且由于没有项目,因此显示参数超出范围异常。
I think that Items are not added before selectedIndex is Binded, and since there are no item, it is showing Argument out of Range exception.
事实证明,ComboBox 控件从根本上就被破坏了。感谢 Rockford Lhotka 的这篇博客文章,我们能够使用以下命令覆盖 ComboBox 控件:可以正确绑定到 SelectedItem 属性的一个。
恶心。
Turns out the ComboBox control was fundamentally broken to begin with. Thanks to this Blog Post by Rockford Lhotka, we were able to override the ComboBox control with one that could correctly bind to SelectedItem property.
Ick.
我会避免从您的选项属性返回新集合。您假设 WPF 仅访问该属性一次。
但您也可以选择使用 CollectionView,其中当前返回 ObservableCollection。如果您使用 MVVM 架构,您的 ViewModel 可以将属性公开为 CollectionView,并且它具有“当前”项目的概念。
I would avoid returning a new collection from your Options property. You're making an assumption that WPF only accesses the property once.
But you also have the option of using a CollectionView where you're currently returning an ObservableCollection. If you're using a MVVM architecture, your ViewModel can expose the property as CollectionView and it has the notion of a "current" item.