[WPF]:列表框的奇怪问题

[WPF]:列表框的奇怪问题,wpf,listbox,Wpf,Listbox,Wpf中的ListBox有一个奇怪的问题,我绑定到ListBox SelectedIndex到viewModel对象中的属性 如果SelectedIndex小于零,则不会选择任何列表框项目。但是,如果SelectedIndex设置为大于列表实际大小的数字,则最后一项仍处于选中状态 当SelectedIndex设置为高于last items索引的值时,是否有方法使列表框不选择最后一项 感谢按照惯例,SelectedIndex为-1表示没有选择;这就是为什么负值不会导致列表框中的选择 为了更紧密地控

Wpf中的ListBox有一个奇怪的问题,我绑定到ListBox SelectedIndex到viewModel对象中的属性

如果SelectedIndex小于零,则不会选择任何列表框项目。但是,如果SelectedIndex设置为大于列表实际大小的数字,则最后一项仍处于选中状态

当SelectedIndex设置为高于last items索引的值时,是否有方法使列表框不选择最后一项


感谢

按照惯例,SelectedIndex为-1表示没有选择;这就是为什么负值不会导致列表框中的选择

为了更紧密地控制选择,您可以绑定到ICollectionView而不是直接绑定到集合(事实上,这是我在执行MVVM时一直建议的),并使用yourView.MoveCurrentTo控制选择。。。方法。 例如:


按照惯例,SelectedIndex为-1表示没有选择;这就是为什么负值不会导致列表框中的选择

为了更紧密地控制选择,您可以绑定到ICollectionView而不是直接绑定到集合(事实上,这是我在执行MVVM时一直建议的),并使用yourView.MoveCurrentTo控制选择。。。方法。 例如:


一个想法可能是不允许所选索引大于上一个索引

public IEnumerable<object> Items {get; protected set;} //your collection
private int m_selectedIndex; //the underlying data for your new property

private int SelectedIndex //bind the SelectedIndex property of the listbox to this
{
    get { return m_index; }
    set
    {
        if (value < Items.Count -1)
            m_index = value;
        else
            m_index = -1;

        PropertyChanged(...)
    }
}
public IEnumerable Items{get;protected set;}//您的集合
私有int m_selectedIndex//新属性的基础数据
private int SelectedIndex//将列表框的SelectedIndex属性绑定到此
{
获取{return m_index;}
设置
{
如果(值<项目计数-1)
m_指数=数值;
其他的
m_指数=-1;
属性更改(…)
}
}

一个想法可能是不允许所选索引大于上一个索引

public IEnumerable<object> Items {get; protected set;} //your collection
private int m_selectedIndex; //the underlying data for your new property

private int SelectedIndex //bind the SelectedIndex property of the listbox to this
{
    get { return m_index; }
    set
    {
        if (value < Items.Count -1)
            m_index = value;
        else
            m_index = -1;

        PropertyChanged(...)
    }
}
public IEnumerable Items{get;protected set;}//您的集合
私有int m_selectedIndex//新属性的基础数据
private int SelectedIndex//将列表框的SelectedIndex属性绑定到此
{
获取{return m_index;}
设置
{
如果(值<项目计数-1)
m_指数=数值;
其他的
m_指数=-1;
属性更改(…)
}
}