1

次のような 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 の最初の項目を選択済みとして設定することです。

前もって感謝します。

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 プロパティを使用します。Xaml:

<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 に答える