【问题标题】:Silverlight and ComboBox: ItemsSource and SelectedIndex workaroundSilverlight 和 ComboBox:ItemsSource 和 SelectedIndex 解决方法
【发布时间】:2011-11-14 19:56:25
【问题描述】:

我有一个如下所示的 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 的第一项设置为选中。

提前谢谢你。

【问题讨论】:

    标签: silverlight combobox itemssource selectedindex


    【解决方案1】:

    将您的UserList 设置为依赖属性并使用DependencyProperty.Register() 中的PropertyChangedCallback 选项。

    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;
    }));
    

    【讨论】:

    • 谢谢。你能给我提供正确的步骤吗?谢谢。
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回复..数据源是什么意思?你能给我提供更多信息吗?再次感谢。
    • 您用于数据的对象。在这种情况下,您正在执行 List<..> 这是非常通用的。 ComboBox 可以处理类似于旧 ComboBoxItem 的不同类型吗?或者,如果 ComboBox 允许您为选定属性绑定到 ItemsSource 的属性,只需将选定属性添加到您的 UserItem 类。
    【解决方案3】:

    为此目标使用 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 2015-06-01
      相关资源
      最近更新 更多