Silverlight 和 ComboBox:ItemsSource 和 SelectedIndex 解决方法
我有一个如下所示的 SL ComboBox:
<ComboBox ItemsSource="{Binding UserList}" DisplayMemberPath="Name" />
其中 UserLists 是:
List<UserItem>
并且每个 UserItem 是:
public class UserItem
{
public int Code { get; set; }
public string Name { get; set; }
}
由于 ItemsSource 属性是通过 Binding 设置的,因此如何将 SelectedIndex 属性设置为零?当我尝试设置此属性时,出现索引超出范围异常。
我的目标是将 UserList 的第一项设置为选定。
先感谢您。
I have a SL ComboBox like the following:
<ComboBox ItemsSource="{Binding UserList}" DisplayMemberPath="Name" />
where UserLists is:
List<UserItem>
and each UserItem is:
public class UserItem
{
public int Code { get; set; }
public string Name { get; set; }
}
Since ItemsSource Property is set by Binding, how is it possible to set SelectedIndex property to zero? When I try to set this property, I have an index out of range exception.
My goal is to set as selected the first item of UserList.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将您的
UserList
设为依赖属性,并使用DependencyProperty.Register()
中的PropertyChangedCallback
选项。Make your
UserList
a dependency property and use thePropertyChangedCallback
option inDependencyProperty.Register()
.您可能会遇到索引超出范围的情况,因为在您指定索引时数据实际上尚未绑定。不幸的是,似乎没有 data_loaded 事件或类似事件可以让您在绑定数据时设置索引。
您可以使用理解选择概念的数据源吗? ComboBox 会尊重该属性吗?
You might be getting an index out of range because the data hasn't actually bound by the time you're specifying the index. Unfortunately there doesn't appear to be a data_loaded event or similar which would let you set the index when the data has been bound.
Could you use a data source that understands the concept of selected? Will ComboBox respect that attribute?
使用 ComboBox 的 SelectedItem 属性来实现此目标。
Xaml:
视图模型:
用于选择集合中的第一个用户使用命令:
Use SelectedItem property of ComboBox for this goal.
Xaml:
View model:
For selecting first user in collection use command: