Reputation: 1452
I am new to the MVVM pattern. I have a form, that includes one TextBox
, and one DataGrid
. My DataGrid
binding with an ObservableCollection
. What I would like is to be able to have the search with TextChanged
event of TextBox
and show result in DataGrid
.
I'm using a TextBox
in the GridView
and its in Model View-View Model. 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? Please help me.Any idea....
Upvotes: 1
Views: 4226
Reputation: 2095
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.
The function triggered in the setter should update the ObservableCollection, which will cause the DataGrid to update its content.
Se the code example below, code wont compile but shows the general idea.
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:
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:
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;
}
}
Upvotes: 1