简体   繁体   English

C# WPF TextBox 在文本更改时调用方法

[英]C# WPF TextBox call method on text change

so I recently started coding a WPF MVVM program in C# for the first time and got into a bit of a problem.所以我最近第一次开始在 C# 中编写 WPF MVVM 程序并遇到了一些问题。 I made a filter TextBox where the user can type in something and it will filter a list according to it.我制作了一个过滤器文本框,用户可以在其中输入一些内容,它会根据它过滤一个列表。 so my XAML looks like this:所以我的 XAML 看起来像这样:

<TextBox Text="{Binding Path=SearchFilter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

So when a user inputs something it updates the SearchFilter and then I want it to run the LoadList() method.因此,当用户输入内容时,它会更新 SearchFilter,然后我希望它运行 LoadList() 方法。 How would I do that without putting any extra call inside the setter of SearchFilter?如果不在 SearchFilter 的设置器中添加任何额外的调用,我将如何做到这一点?

So I've completly missed something on my side, sorry for that.所以我完全错过了我身边的一些东西,对此感到抱歉。 This approach should help you.这种方法应该对您有所帮助。

XAML XAML

<TextBox Text="{Binding SearchFilter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
               TextChanged="TextBox_TextChanged"/>

Code Behind代码背后

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
  var viewmodel = DataContext as ViewModel1;

  viewmodel.LoadList();
}

In my case this is the ViewModel class, you should try using INotifyPropertyChanged as it will update your UI if you change something in the code and you will need it probably in the future anyways.在我的情况下,这是 ViewModel class,您应该尝试使用 INotifyPropertyChanged,因为如果您更改代码中的某些内容,它会更新您的 UI,并且您可能在将来可能需要它。 Also this uses SetProperty which makes it just all cleaner and easier这也使用了 SetProperty 这使得它变得更干净、更容易

public class ViewModel1 : INotifyPropertyChanged
{
  public string Title { get; } = "View 1";

  private string _searchFilter;
  public string SearchFilter 
  {
    get { return _searchFilter; }
    set 
    { 
      SetProperty(ref _searchFilter, value);
    }
  }

  public void LoadList()
  {
    Console.WriteLine("Value: "+SearchFilter);
    // your stuff you do in LoadList
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged(string propertyName)
  {
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));  
  }
  protected bool SetProperty<T>(ref T field, T value,
      [CallerMemberName] string propertyName = null)
  {
    if (EqualityComparer<T>.Default.Equals(field, value)) return false;
    field = value;
    OnPropertyChanged(propertyName);
    return false;
  }
}

Btw.顺便提一句。 sry for the past answer, I missed something that I always forget on this specific problem:/对于过去的答案,我错过了一些我在这个特定问题上总是忘记的东西:/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM