TextBox 内容不绑定到源 WPF DataGrid

TextBox content doesn't bind to source WPF DataGrid

我是 WPF 的新手,遇到了一个问题。 我有一个 MVVM WPF 应用程序,我想对我的 DataGrid 实施过滤。我已经尝试了互联网上所有可能的解决方案,但出于某种原因,其中 none 对我有用。我创建了一个 TextBox 并将其绑定到 FilterName。我想要它做的是在每次按键时,应该更新 FilterName 的值并且应该触发过滤器。不幸的是,过滤器只触发一次 - 当我启动应用程序并在 FilterNameSet 块中放置一个断点时,我发现它永远不会到达它。 这是文本框的声明:

 <TextBox
         x:Name="FilterName"
         MinWidth="150"
         Margin="{StaticResource SmallTopBottomMargin}"
         Background="Transparent"
         BorderThickness="0,0,0,1"
         Text="{Binding FilterName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}"
         TextWrapping="Wrap" />

这是 ViewModel:

        private readonly ObservableCollection<PersonData> _data;

        public ICollectionView DataCollectionView { get; }

        private string _filterName = string.Empty;

        public string FilterName
        {
            get
            {
                return _filterName;
            }
            set
            {
                _filterName = value;
                DataCollectionView.Refresh();
            }
        }

        public MainWindowViewModel(ISampleDataService sampleDataService)
        {
            //Adding the data here            

            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;
        }
  1. 将 window 的名称设置为 x:Name="_this" 并更改 TextBox 绑定:
<TextBox   
    x:Name="tbFilterName"  
    DataContext="{Binding ElementName=_this}"                 
    Text="{Binding Path=FilterName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
    TextChanged="FilterName_TextChanged"      
    ...
  1. FilterName setter 中删除 DataCollectionView.Refresh(); 调用,但添加
private void FilterName_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
    DataCollectionView.Refresh();
}

如果具有 FilterName 属性 的视图模型是父 window:

DataContext,则此绑定应该有效
Text="{Binding DataContext.FilterName, UpdateSourceTrigger=PropertyChanged, 
        RelativeSource={RelativeSource AncestorType=Window}}"