Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hookup TextBox's TextChanged event and Command in order to use MVVM pattern in Silverlight

Tags:

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 textChanged event with Command? There is Command property for Button, however Textbox has no commapd property. If Controls don't have command property, how to combine ICommand and Control's event?

I got following xaml code

<UserControl.Resources>         <vm:CustomerViewModel x:Key="customerVM"/>         </UserControl.Resources>      <Grid x:Name="LayoutRoot"            Background="White"            DataContext="{Binding Path=Customers, Source={StaticResource customerVM}, Mode=TwoWay}" >          <StackPanel>             <StackPanel Orientation="Horizontal"                         Width="300"                         HorizontalAlignment="Center">                 <TextBox x:Name="tbName"                           Width="50"                           Margin="10"/>                 <Button Width="30"                          Margin="10"                          Content="Find"                         Command="{Binding Path=GetCustomersByNameCommand, Source={StaticResource customerVM}}"                         CommandParameter="{Binding Path=Text, ElementName=tbName}"/>             </StackPanel>             <sdk:DataGrid ItemsSource="{Binding Path=DataContext, ElementName=LayoutRoot}"                           AutoGenerateColumns="True"                           Width="300"                           Height="300"/>         </StackPanel>     </Grid> 

What I am trying to do is that if user input some text in the textbox, data will be shown in the datagrid instead of using button click. I know there is autocomplete box control built in. however, I want to know how to call Command property in the ViewModel class in the controls which does not have Command property such as textbox.

Thanks

like image 771
Ray Avatar asked Aug 16 '10 08:08

Ray


1 Answers

Why not just bind the Text property to a property on your view model? That way you get notified when it has changed, and also get the new value:

public string MyData {     get { return this.myData; }     set     {         if (this.myData != value)         {             this.myData = value;             this.OnPropertyChanged(() => this.MyData);         }     } } 

XAML:

<TextBox Text="{Binding MyData}"/> 
like image 57
Kent Boogaart Avatar answered Oct 05 '22 23:10

Kent Boogaart