简体   繁体   English

GridView WPF MVVM中TextBox的TextChanged事件

[英]TextChanged event of TextBox in GridView WPF MVVM

I am new to the MVVM pattern. 我是MVVM模式的新手。 I have a form, that includes one TextBox , and one DataGrid . 我有一个窗体,其中包括一个TextBox和一个DataGrid My DataGrid binding with an ObservableCollection . 我的DataGridObservableCollection绑定。 What I would like is to be able to have the search with TextChanged event of TextBox and show result in DataGrid . 我想要的是能够使用TextBox TextChanged事件进行搜索并在DataGrid显示结果。

I'm using a TextBox in the GridView and its in Model View-View Model. 我在GridView及其模型视图-视图模型中使用TextBox Basically, what I want to do is call a method every time the text in the box is edited. 基本上,我想做的是每次编辑框中的文本时调用一个方法。 That is when the text is entered, the function will call. 即在输入文本时,该函数将调用。 That is the text change event should work. 那就是文本更改事件应该起作用。 But in Model View-View Model, what can I do? 但是在Model View-View Model中,我该怎么办? Please help me.Any idea.... 请帮助我。任何想法...。

You trigger the function in the setter of the property that you bind to the textbox. 您在绑定到文本框的属性的设置器中触发函数。 You also have to set UpdateSourceTrigger of the binding to PropertyChanged in order to get it to trigger everytime you change the content of the textbox. 您还必须将绑定的UpdateSourceTrigger设置为PropertyChanged,以使其在每次更改文本框的内容时触发。

The function triggered in the setter should update the ObservableCollection, which will cause the DataGrid to update its content. 在setter中触发的函数应更新ObservableCollection,这将导致DataGrid更新其内容。

Se the code example below, code wont compile but shows the general idea. 在下面的代码示例中,代码不会编译,但显示了总体思路。

xaml: XAML:

<DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Text}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

SubviewModel.cs: SubviewModel.cs:

public SubViewModel(ViewModel vm)
{
  _vm = vm;
}

private string _text;
private ViewModel _vm;

public string Text
{
  get 
  {
    return _text;
  }
  set
  {
    if (_text == value)
    {
      return;
    }

    _text = value;
    OnPropertyChanged("Text");
    RefreshResult();
}

private void RefreshResult()
{
  // Do something with the _text and manipulate the _vm.Rows?
}

ViewModel.cs: ViewModel.cs:

private ObservableCollection<SubViewModel> _rows;
public ViewModel()
{
   //Initialize the sub view models
   _rows = new ObservableCollection<SubViewModel>();

   //Populate the list somehow
   foreach (var r in sourceOfRows)
   {
      _rows.Add(new SubViewModel(this));
   }
}

public ObservableCollection<SubViewModels> Rows
{
  get 
  {
    return _rows;
  }
}

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

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