您已创建一个绑定到计算机列表的列表框。随着机器数量的急剧增加,我需要以某种方式按名称进行过滤。出于这个原因,我提供了一个TextBox,用户可以在其中引入一个字符串来过滤掉。 我曾想过创建另一个列表,它将绑定到视图,即第二个列表,仅用于可视化。但是,我认为必须有一个更清洁的方法来做到这一点。
<ListBox IsSynchronizedWithCurrentItem="True" Visibility="{Binding MachinesPanelVisibility}"
ItemsSource="{Binding MachineRulesList}" SelectedIndex="{Binding ItemSelectionIndex}" />
<TextBox HorizontalAlignment="Right" Width="162" Text="Filter..." TextWrapping="Wrap" Margin="0,44,18,13" />
在viewModel上:
public class BusinessRulesWizardViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> MachineRulesList
{
get { return _machineRulesList; }
set
{
_machineRulesList = value;
OnPropertyChanged("MachineRulesList");
}
}
public BusinessRulesWizardViewModel(ISystemView systemViewManager,
IEventAggregator eventAggregator)
{
_machineRulesList = new ObservableCollection<string>();
_systemViewManager.GetMachines(page, pageSize).ToList().ForEach(
item => _machineRulesList.Add(item)
);
}
答案 0 :(得分:2)
使用可以使用ICollectionView接口将Filter
属性设置的集合包装为使用TextBox
中输入的文本的谓词。这是一个例子:
<ListBox IsSynchronizedWithCurrentItem="True" Visibility="{Binding MachinesPanelVisibility}"
ItemsSource="{Binding MachineRulesListView}"
SelectedIndex="{Binding ItemSelectionIndex}" />
<TextBox HorizontalAlignment="Right" Width="162"
Text="{Binding FilterText}"
TextWrapping="Wrap" Margin="0,44,18,13" />
-
public class BusinessRulesWizardViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> MachineRulesList
{
get { return _machineRulesList; }
set
{
_machineRulesList = value;
OnPropertyChanged("MachineRulesList");
}
}
public string FilterText
{
get { return _filterText; }
set
{
_filterText= value;
OnPropertyChanged("FilterText");
MachineRulesListView.Refresh();
}
}
public ICollectionView MachineRulesListView { get; private set; }
public BusinessRulesWizardViewModel(ISystemView systemViewManager, IEventAggregator eventAggregator)
{
_machineRulesList = new ObservableCollection<string>();
MachineRulesListView = CollectionViewSource.GetDefaultView(_machineRulesList);
MachineRulesListView.Filter = new Predicate<object>(r => ((string)r).Contains(FilterText));
_systemViewManager.GetMachines(page, pageSize).ToList().ForEach(
item => _machineRulesList.Add(item)
);
}
}