我有一个带有文本框的用户控件和一个自定义列表控件,该控件基本上是带有 CollectionView 的 ListBox。我想使用 CollectionView 的过滤功能并使用文本框中的文本来过滤可见元素。
xaml 的简化表示:
<TextBox x:Name="FilterTextControl"/>
<CustomControls:OverviewControl
x:Name="ProfileOverviewControl"
FilterText="{Binding ElementName=FilterTextControl, Path=Text, Mode=OneWay, Delay=5000}"
Items="{Binding AllItems}"/>
Collection View 源:
<CollectionViewSource x:Key="GroupedProfiles"
Source="{Binding Items, RelativeSource={RelativeSource AncestorType=local:OverviewControl}}"
Filter="GroupedProfiles_OnFilter">
<CollectionViewSource.SortDescriptions>
<componentModel:SortDescription PropertyName="Location" />
<componentModel:SortDescription PropertyName="Description" />
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Location" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
OverviewControl 中的 FilterText 依赖属性:
public string FilterText
{
get => (string)GetValue(FilterTextProperty);
set => SetValue(FilterTextProperty, value);
}
public static readonly DependencyProperty FilterTextProperty =
DependencyProperty.Register(nameof(FilterText), typeof(string),
typeof(ProfileOverviewControl), new FrameworkPropertyMetadata(OnFilterTextChanged));
private static void OnFilterTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var intanceOfThisClass = (ProfileOverviewControl)d;
if (_collectionViewSource == null)
_collectionViewSource = intanceOfThisClass.FindResource("GroupedProfiles") as CollectionViewSource;
_collectionViewSource?.View?.Refresh();
}
OnFilterEvent 方法:
private void GroupedProfiles_OnFilter(object sender, FilterEventArgs e)
{
e.Accepted = string.IsNullOrEmpty(FilterText) || e.Item.ToString().Contains(FilterText);
}
问题
正如您在 FilterText 的绑定(bind)中看到的,我有 5000 毫秒的延迟。出于测试目的,我将其设置为 5000 毫秒,而不是合理的 500 毫秒。 为了使过滤器正常工作,我需要刷新 CollectionView。 但是,PropertyChangedCallback 在每次更改后立即触发,而不是通过延迟绑定(bind)来限制它。
我不太理解这种行为。如果这就是延迟绑定(bind)的工作原理,是否有其他方法可以限制 CollectionView 刷新?
最佳答案
尝试像这样反转绑定(bind)。这样,延迟将发生在文本框更改上。现在延迟发生在过滤器属性更改上(如果从 OverviewControl 更改)。
<TextBox x:Name="FilterTextControl" Text="{Binding ElementName=ProfileOverviewControl, Path=FilterText, Delay=5000}"/>
<CustomControls:OverviewControl
x:Name="ProfileOverviewControl"
Items="{Binding AllItems}"/>
关于c# - DependencyProperty 的 PropertyChangedCallback 忽略延迟绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449162/