在 c# wpf 中筛选组合框



XAML:

<ComboBox x:Name="cmb" HorizontalAlignment="Left" 
Margin="183,39,0,0" 
VerticalAlignment="Top" 
Width="120" 
ItemsSource="{Binding FilteredNames, Mode=OneWay}"
IsTextSearchEnabled="True"
IsEditable="True"
TextSearch.Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged}"/>

视图模型:

public List<string> FilteredNames
{
get
{
return (names.FindAll(x => x.Contains(filter))).ToList<string>();
}
}
public string Filter
{
get
{
return this.filter;
}
set
{
this.filter = value;
NotifyPropertyChanged("FilteredNames");
}
}
public ViewModel()
{
this.names = new List<string>() { "Jerry", "Joey", "Roger", "Raymond", "Jessica", "Mario", 
"Jonathan" };
this.filter = "";
}

这就是我实施的。请帮助我如何在组合框中获取过滤下拉列表。 就像我输入"j"时一样,我想获取其中包含"j"的所有项目。

应将字符串输入绑定到 ComboBox 的 Text 属性:

Text="{Binding Filter, UpdateSourceTrigger=PropertyChanged}"

另外,我建议使用CollectionView进行这样的过滤:

public ICollectionView FilteredNames { get; set; }
IList<string> names = new List<string>() { "Jerry", "Joey", "Roger", "Raymond", "Jessica", "Mario", "Jonathan" };
public VM()
{
FilteredNames = CollectionViewSource.GetDefaultView(names);
FilteredNames.Filter = (obj) => 
{
if (!(obj is string str))
return false;
return str.Contains(filter);
};
}
string filter = "";
public string Filter
{
get 
{
return this.filter;
}
set 
{
this.filter = value;
FilteredNames?.Refresh();
}
}

最新更新