[英]Can I bind to the first item of a CollectionView?
I'm binding a ListBox
to an ICollectionView
defined on the ViewModel (VM from now). 我将一个ListBox
绑定到在ViewModel(从现在开始的VM)上定义的ICollectionView
上。 I have a property for the selected item ( SelectedFoo
) that is set to be the first in the VM constructor. 我具有所选项目的属性( SelectedFoo
),该属性设置为VM构造函数中的第一个属性。
When someone enters text in a textbox, I filter the collection based on that input (so far, so good). 当有人在文本框中输入文本时,我会根据该输入过滤集合(到目前为止,很好)。
How can I set the selected index to be the first item in the collection after some filtering was applied? 应用某些过滤后,如何将所选索引设置为集合中的第一项? I can't bind to the first object in the ICollectionView
from the code. 我无法从代码绑定到ICollectionView
的第一个对象。
Any ideas? 有任何想法吗?
Here's some stripped down code, including the List
, the ICollectionView
that I bind to in the XAML, and the code that filters is in the FooFilterString
which is updated as the user types into the text box. 这是一些简化的代码,包括List
,我在XAML中绑定到的ICollectionView
以及用于过滤的代码在FooFilterString
,随着用户在文本框中键入内容,该代码将更新。
// This is the underlying list
public List<Foo> FooList
{
get { return _fooList; }
set
{
if (Equals(value, _fooList)) return;
_fooList = value;
RaisePropertyChanged();
}
}
private List<Foo> _fooList;
// This is what the list box binds to
public ICollectionView FooListView
{
get { return _fooListView; }
set
{
if (Equals(value, _fooListView)) return;
_fooListView = value;
RaisePropertyChanged();
}
}
private ICollectionView _fooListView ;
// This is bound to from the XAML, as user types, it will filter the list.
// I want to bind to the first item of the filtered list.
public string FooFilterString
{
get { return _fooFilterString; }
set
{
_fooFilterString = value;
FooListView.Filter = (s => some_logic); // <-- filters the list
/*
* How can I set the selected index here ?!
*/
}
}
private string _fooFilterString;
// I Bind to this, and want to set this after filtering. First time, I just
// set it to the first item from the FooList, but after filtering, I'm loosing
// the selection
public Foo SelectedFoo {
get { /*...*/ }
set { /*...*/ }
}
private Foo _selectedFoo;
To sum up comments to select first item from ICollectionView
you can use ICollectionView.MoveCurrentToFirst()
要汇总注释以从ICollectionView
选择第一项,可以使用ICollectionView.MoveCurrentToFirst()
FooListView.Filter = s => some_logic;
FooListView.MoveCurrentToFirst()
you'll also need to enable IsSynchronizedWithCurrentItem
您还需要启用IsSynchronizedWithCurrentItem
<ListBox ... IsSynchronizedWithCurrentItem="True">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.