GridView WPF MVVM 中文本框的文本更改事件



我是MVVM模式的新手。我有一个表格,其中包括一个TextBox和一个DataGrid。我的DataGridObservableCollection绑定.我希望能够搜索TextChanged TextBox事件并在DataGrid中显示结果。

我在GridView中使用TextBox及其在模型视图视图中。基本上,我想做的是在每次编辑框中的文本时调用一个方法。也就是说,当输入文本时,函数将调用。那就是文本更改事件应该工作。但是在模型视图-视图模型中,我能做什么?请帮助我。任何想法....

在绑定到文本框的属性的 setter 中触发函数。您还必须将绑定的 UpdateSourceTrigger 设置为 PropertyChanged 以便每次更改文本框的内容时触发它。

在资源库中触发的函数应更新 ObservableCollection,这将导致 DataGrid 更新其内容。

Se 下面的代码

示例,代码不会编译,但显示了一般思想。

XAML:

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

子视图模型.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?
}

视图模型.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;
  }
}

最新更新