You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF DataGrid过滤场景中TextBox绑定属性Set块未触发问题

WPF DataGrid过滤功能失效修复方案

  • 移除TextBox绑定中的IsAsync=True参数
    IsAsync是用于异步读取源属性值的特殊配置,会破坏双向绑定的实时回写逻辑,是你的FilterName属性set方法始终不触发的直接原因。修改后的绑定代码如下:
<TextBox
         x:Name="FilterName"
         MinWidth="150"
         Margin="{StaticResource SmallTopBottomMargin}"
         Background="Transparent"
         BorderThickness="0,0,0,1"
         Text="{Binding FilterName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         TextWrapping="Wrap" />
  • 为ViewModel实现INotifyPropertyChanged接口
    WPF双向绑定要求源对象实现属性变更通知机制,否则部分场景下绑定无法正常同步值,同时也能支持后续从ViewModel侧更新FilterName时UI自动同步。修改后的ViewModel代码如下:
using System.ComponentModel;
using System.Runtime.CompilerServices;

// 让ViewModel继承INotifyPropertyChanged接口
public class MainWindowViewModel : INotifyPropertyChanged
{
    private readonly ObservableCollection<PersonData> _data;
    public ICollectionView DataCollectionView { get; }

    // 实现属性变更通知事件
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _filterName = string.Empty;
    public string FilterName
    {
        get => _filterName;
        set
        {
            // 避免重复赋值触发不必要的刷新
            if (_filterName == value) return;
            _filterName = value;
            OnPropertyChanged();
            DataCollectionView.Refresh();
        }
    }

    public MainWindowViewModel(ISampleDataService sampleDataService)
    {
        // 此处保留原有数据加载逻辑           
        DataCollectionView = CollectionViewSource.GetDefaultView(_data);
        DataCollectionView.Filter = FilterByName;
    }

    private bool FilterByName(object obj)
    {
        if (obj is PersonData data)
        {
            return data.Name.Contains(FilterName, StringComparison.InvariantCultureIgnoreCase);
        }
        return false;
    }
}
  • 验证DataContext绑定正确性
    确保承载TextBox的窗口/用户控件的DataContext已正确关联到MainWindowViewModel的实例,示例配置如下:
public MainWindow()
{
    InitializeComponent();
    // 替换为你实际的依赖注入/实例化逻辑
    DataContext = new MainWindowViewModel(new SampleDataService());
}

内容的提问来源于stack exchange,提问作者Raya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:54:03