Recently, I realized that MVVM pattern is so useful for Silverlight application and studying how to adopt it into my project.
BTW, how to hook up the textbox\'s text
I solved it by binding to a property on my view model and setting the binding's UpdateSourceTrigger to PropertyChanged. The property supports INotifyPropertyChanged.
In my view model I then subscribe to the PropertyChanged event for the property. When it triggers I perform the tasks I need to do (in my case updating a collection) and at the end I call PropertyChanged on the property that my other stuff in the view is listening to.
Here's the MvvmLight way of doing it! Credit goes to GalaSoft Laurent Bugnion.
<sdk:DataGrid Name="dataGrid1" Grid.Row="1"
ItemsSource="{Binding Path=CollectionView}"
IsEnabled="{Binding Path=CanLoad}"
IsReadOnly="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand
Command="{Binding SelectionChangedCommand}"
CommandParameter="{Binding SelectedItems, ElementName=dataGrid1}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</sdk:DataGrid>
Source: http://blog.galasoft.ch/archive/2010/05/19/handling-datagrid.selecteditems-in-an-mvvm-friendly-manner.aspx
Jeremy answered it. However, if you want to reduce code behind just do something like this. In your view model:
public class MyViewModel
{
private string _myText;
public string MyText
{
get { return _myText; }
set
{
_myText = value;
RaisePropertyChanged("MyText"); // this needs to be implemented
// now do whatever grid refresh/etc
}
}
public void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var binding = ((TextBox)sender).GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
}
Then in code behind:
public void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
YourViewModel.TextBox_TextChanged(sender, e);
}
I know it's duplicated code, but if this is what you want, then here it is.
In the definition section we add:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
If you use the TextBox
, add the reference to the event we want to detect:
<TextBox Text="{Binding TextPrintersFilter}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding FilterTextChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
In the ViewModel add code for Commad:
public ICommand FilterTextChangedCommand
{
get
{
if (this._filterTextChangedCommand == null)
{
this._filterTextChangedCommand =
new RelayCommand(param => this.OnRequestFilterTextChanged());
}
return this._filterTextChangedCommand;
}
}
private void OnRequestFilterTextChanged()
{
// Add code
}
Do not forget to perform the binding text:
private string _textPrintersFilter;
public string TextPrintersFilter
{
get { return _textPrintersFilter; }
set
{
_textPrintersFilter = value;
this.RaisePropertyChange(nameof(TextPrintersFilter));
}
}