在WPF中仅使用XAML根据TextBox的文本筛选ListBox的项

本文关键字:TextBox 文本 筛选 的项 ListBox 根据 XAML WPF | 更新日期: 2023-09-27 18:05:57

我目前有一个ListBox绑定到一个项目集合。由于集合很大,我们希望根据在TextBox上输入的文本过滤显示的项目。

我想问的是,如果这是可能实现仅使用XAML,我不想修改项目的集合,我想修改基于过滤器的每个项目的可见性。

希望它清楚,

谢谢!

在WPF中仅使用XAML根据TextBox的文本筛选ListBox的项

就像CodeNaked和devdigital告诉你CollectionViewSource/CollectionView/ICollectionView是你实现目标的关键

这是一个MVVM模式,但这是一个视图只相关的问题,所以我没有

这不是正确的方式,因为视图只显示她得到的东西,而不应该修改所以它应该/必须是你的ViewModel谁来处理更改

那么现在一些代码片段:

    public class myVM
    {
        public CollectionViewSource CollViewSource { get; set; }
        public string SearchFilter
        {
            get;
            set
            {
              if(!string.IsNullOrEmpty(SearchFilter))
                 AddFilter();
                CollViewSource.View.Refresh(); // important to refresh your View
            }
        }
        public myVM(YourCollection)
        {
            CollViewSource = new CollectionViewSource();//onload of your VM class
            CollViewSource.Source = YourCollection;//after ini YourCollection
        }
    }
Xaml剪:

    <StackPanel>
        <TextBox Height="23" HorizontalAlignment="Left"  Name="tB" VerticalAlignment="Top" 
                 Width="120" Text="{Binding SearchFilter,UpdateSourceTrigger=PropertyChanged}" />
        <DataGrid Name="testgrid" ItemsSource="{Binding CollViewSource.View}"/>
    </StackPanel>

编辑我忘了滤镜

private void AddFilter()
{
    CollViewSource.Filter -= new FilterEventHandler(Filter);
    CollViewSource.Filter += new FilterEventHandler(Filter);  
}
private void Filter(object sender, FilterEventArgs e)
{
    // see Notes on Filter Methods:
    var src = e.Item as YourCollectionItemTyp;
    if (src == null)
        e.Accepted = false;
    else if ( src.FirstName !=null && !src.FirstName.Contains(SearchFilter))// here is FirstName a Property in my YourCollectionItem
        e.Accepted = false;
}

您可以使用CollectionViewSource来应用过滤,另一个例子可以在这里和这里找到。

您可以使用CollectionViewSource来做到这一点。您不希望完全在XAML中执行此操作,因为如果过滤代码位于视图模型中(假设是MVVM设计模式),则测试此操作要容易得多。

仅在XAML中无法完成此操作。但还有另外两种方法:1)使用转换器

<TextBox x:Name="text"/>
<ListBox Tag="{Binding ElementName=text}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource AncestorType=ListBox},Path=Tag, Converter={StaticResource filterLogicConverter}}"/>
</Style>
</ListBox.ItemContainerStyle>
<LixtBox/>

2)更好和更自然的方法是使用CollectionView。过滤器属性。它不修改底层集合。

var collectionView = CollectionViewSource.GetDefaultView(your_collection);
collectionView.Filter = filter_predicate

XAML真正做的唯一事情是以声明的方式封装逻辑。使用标记扩展可以做很多事情,下面是一个例子:

<StackPanel>
    <StackPanel.Resources>
        <CollectionViewSource x:Key="items" Source="{Binding Data}">
            <CollectionViewSource.Filter>
                <me:Filter>
                    <me:PropertyFilter PropertyName="Name"
                            RegexPattern="{Binding Text, Source={x:Reference filterbox}}" />
                </me:Filter>
            </CollectionViewSource.Filter>
        </CollectionViewSource>
    </StackPanel.Resources>
    <TextBox Name="filterbox" Text="Skeet">
        <TextBox.TextChanged>
            <me:ExecuteActionsHandler ThrowOnException="false">
                <me:CallMethodAction>
                    <me:CallMethodActionSettings MethodName="Refresh"
                            TargetObject="{Binding Source={StaticResource items}}" />
                </me:CallMethodAction>
            </me:ExecuteActionsHandler>
        </TextBox.TextChanged>
    </TextBox>
    <!-- ListView here -->
</StackPanel>

(注意,这是有效的,但它会绊倒每个GUI设计人员,而且事件没有智能感知,因为它们通常不是通过元素语法设置的。)

这里有几个标记扩展,其中两个创建处理程序,一个创建操作:

  • FilterExtension
  • ExecuteActionsHandlerExtension
  • CallMethodActionExtension

扩展如下:

[ContentProperty("Filters")]
class FilterExtension : MarkupExtension
{
    private readonly Collection<IFilter> _filters = new Collection<IFilter>();
    public ICollection<IFilter> Filters { get { return _filters; } }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new FilterEventHandler((s, e) =>
            {
                foreach (var filter in Filters)
                {
                    var res = filter.Filter(e.Item);
                    if (!res)
                    {
                        e.Accepted = false;
                        return;
                    }
                }
                e.Accepted = true;
            });
    }
}
public interface IFilter
{
    bool Filter(object item);
}

非常简单,只是循环遍历过滤器并应用它们。ExecuteActionsHandlerExtension:

也一样
[ContentProperty("Actions")]
public class ExecuteActionsHandlerExtension : MarkupExtension
{
    private readonly Collection<Action> _actions = new Collection<Action>();
    public Collection<Action> Actions { get { return _actions; } }
    public bool ThrowOnException { get; set; }
    public ExecuteActionsHandlerExtension()
    {
        ThrowOnException = true;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new RoutedEventHandler((s, e) =>
            {
                try
                {
                    foreach (var action in Actions)
                    {
                        action.Invoke();
                    }
                }
                catch (Exception)
                {
                    if (ThrowOnException) throw;
                }
            });
    }
}

现在最后一个扩展有点复杂,因为它实际上需要做一些具体的事情:

[ContentProperty("Settings")]
public class CallMethodActionExtension : MarkupExtension
{
    //Needed to provide dependency properties as MarkupExtensions cannot have any
    public CallMethodActionSettings Settings { get; set; }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new Action(() =>
            {
                bool staticCall = Settings.TargetObject == null;
                var argsCast = Settings.MethodArguments.Cast<object>();
                var types = argsCast.Select(x => x.GetType()).ToArray();
                var args = argsCast.ToArray();
                MethodInfo method;
                if (staticCall)
                {
                    method = Settings.TargetType.GetMethod(Settings.MethodName, types);
                }
                else
                {
                    method = Settings.TargetObject.GetType().GetMethod(Settings.MethodName, types);
                }
                method.Invoke(Settings.TargetObject, args);
            });
    }
}
public class CallMethodActionSettings : DependencyObject
{
    public static readonly DependencyProperty MethodNameProperty =
        DependencyProperty.Register("MethodName", typeof(string), typeof(CallMethodActionSettings), new UIPropertyMetadata(null));
    public string MethodName
    {
        get { return (string)GetValue(MethodNameProperty); }
        set { SetValue(MethodNameProperty, value); }
    }
    public static readonly DependencyProperty TargetObjectProperty =
        DependencyProperty.Register("TargetObject", typeof(object), typeof(CallMethodActionSettings), new UIPropertyMetadata(null));
    public object TargetObject
    {
        get { return (object)GetValue(TargetObjectProperty); }
        set { SetValue(TargetObjectProperty, value); }
    }
    public static readonly DependencyProperty TargetTypeProperty =
        DependencyProperty.Register("TargetType", typeof(Type), typeof(CallMethodActionSettings), new UIPropertyMetadata(null));
    public Type TargetType
    {
        get { return (Type)GetValue(TargetTypeProperty); }
        set { SetValue(TargetTypeProperty, value); }
    }
    public static readonly DependencyProperty MethodArgumentsProperty =
        DependencyProperty.Register("MethodArguments", typeof(IList), typeof(CallMethodActionSettings), new UIPropertyMetadata(null));
    public IList MethodArguments
    {
        get { return (IList)GetValue(MethodArgumentsProperty); }
        set { SetValue(MethodArgumentsProperty, value); }
    }
    public CallMethodActionSettings()
    {
        MethodArguments = new List<object>();
    }
}

所有这些片段只是演示如何处理这个问题的快速草稿。(属性过滤器实现的草稿可以在这个回答中找到。)

对集合中项目的某些属性使用数据触发器,您可以在xaml中完成所有操作。