【发布时间】:2018-11-27 01:48:50
【问题描述】:
WPF 和 MVVM 的新手。我正在尝试将带有 FilterEventHandler 的过滤器用于 CollectionViewSource。我正在尝试在属性更改 (p_sSelectedCreatedDate) 中添加过滤器。问题是当我将过滤器添加到 CollectionViewSource 对象时,FilterEventHandler 委托函数(FilterByCreatedDate)没有触发。当我调试时,我可以在代码中看到正在添加过滤器,如下行所示。
CVS.Filter += new FilterEventHandler(FilterByCreatedDate);
但是,代码返回而不执行 FilterByCreatedDate。 请注意,我只发布此问题所需的代码部分和继承自 INotifyPropertyChanged 的 BaseViewModel。
以下是必要的代码。
ScanBatchWindow.xaml
<Window x:Class="BatchManPOC.ScanBatchWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BatchManPOC"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmdBehavior="clr-namespace:BatchManPOC.CmdBehavior"
xmlns:video="clr-namespace:BatchManPOC.Video"
xmlns:Custom="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
mc:Ignorable="d"
Title="ScanBatchWindow"
Height="800"
Width="800">
<Window.Resources>
<CollectionViewSource Source="{Binding p_ListBatches}" x:Key="CVS"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Custom:DataGrid ItemsSource="{Binding Source={StaticResource CVS}}" Margin="8" Grid.Row="0" AutoGenerateColumns="True" IsReadOnly="True">
</Custom:DataGrid>
</Grid>
</Window>
ScanBatchViewModel.cs
public class ScanBatchViewModel : BaseViewModel
{
public ObservableCollection<Batch> p_ListBatches { get; set; }
public CollectionViewSource CVS { get; set; }
private string _p_sSelectedCreatedDate;
public string p_sSelectedCreatedDate {
get
{
return _p_sSelectedCreatedDate;
}
set
{
_p_sSelectedCreatedDate = value;
ApplyFilter(!string.IsNullOrEmpty(_p_sSelectedCreatedDate) ? FilterField.CREATED_DATE : FilterField.NONE);
}
}
public ScanBatchViewModel()
{
p_ListBatches = new ObservableCollection<Batch>();
LoadBatches();
CVS = new CollectionViewSource();
}
private void ApplyFilter(FilterField field)
{
switch (field)
{
case FilterField.CREATED_DATE:
AddCreatedDateFilter();
break;
default:
break;
}
}
public void AddCreatedDateFilter()
{
// see Notes on Adding Filters:
if (p_bCanRemoveCreatedDateFilter)
{
CVS.Filter -= new FilterEventHandler(FilterByCreatedDate);
CVS.Filter += new FilterEventHandler(FilterByCreatedDate);
}
else
{
CVS.Filter += new FilterEventHandler(FilterByCreatedDate);
p_bCanRemoveCreatedDateFilter = true;
}
}
private void FilterByCreatedDate(object sender, FilterEventArgs e)
{
// see Notes on Filter Methods:
var src = e.Item as Batch;
if (src == null)
e.Accepted = false;
else if (string.Compare(p_sSelectedCreatedDate, src.Date) != 0)
e.Accepted = false;
}
}
【问题讨论】:
标签: wpf mvvm filter eventhandler collectionviewsource