1

我有一个 SL ComboBox,如下所示:

<ComboBox ItemsSource="{Binding UserList}" DisplayMemberPath="Name" />

其中用户列表是:

List<UserItem>

每个 UserItem 是:

public class UserItem
{
  public int Code { get; set; }
  public string Name { get; set; }
}

由于 ItemsSource 属性是由 Binding 设置的,那么如何将 SelectedIndex 属性设置为零?当我尝试设置此属性时,我有一个索引超出范围异常。

我的目标是将 UserList 的第一项设置为选中。

先感谢您。

4

3 回答 3

2

UserList创建一个依赖属性并PropertyChangedCallback使用.DependencyProperty.Register()

public ObservableCollection<UserItem> UserList
{
   get { return (ObservableCollection<UserItem>)GetValue(UserListProperty); }
   set { SetValue(UserListProperty, value); }
}

public static readonly DependencyProperty UserListProperty = DependencyProperty.Register("UserList", typeof(ObservableCollection<UserItem>), typeof(MainPage), new PropertyMetadata((s, e) =>
{      
   cmbUserList.SelectedIndex = 0;
}));
于 2011-11-14T20:11:10.080 回答
1

您可能会得到超出范围的索引,因为在您指定索引时数据实际上并未绑定。不幸的是,似乎没有 data_loaded 事件或类似事件可以让您在绑定数据时设置索引。

你能使用理解选择概念的数据源吗?ComboBox 会尊重该属性吗?

于 2011-11-14T20:00:32.653 回答
1

为此目标使用 ComboBox 的 SelectedItem 属性。xml:

<ComboBox ItemsSource="{Binding UserList}" SelectedItem="{Binding SelectedUser, Mode=TwoWay}" DisplayMemberPath="Name" />

查看型号:

public ObservableCollection<UserItem> UserList { get; set; }

private UserItem _selectedUser;
public UserItem SelectedUser
{
   get { return _selectedUser; }
   set { _selectedUser = value; }
}

要在集合中选择第一个用户,请使用命令:

//NOTE: UserList must not be null here   
SelectedUser = UserList.FirstOrDefault();
于 2011-11-15T07:00:16.443 回答