简体   繁体   中英

WPF TextBox Trigger

i have the following xaml :

 <Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4" 
    x:Class="WpfApplication4.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <TextBox Margin="89,116,69,123" x:Name="txtFilter" Background="AliceBlue" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <cmd:EventToCommand Command="{Binding MyClass:SearchedTextChanged}" CommandParameter="{Binding Text, ElementName=txtFilter}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
    <TextBox Width="100"  Background="AntiqueWhite">
    </TextBox>

And the code is as follows:

public partial class MainWindow: Window

{
        public MainWindow()
 {

InitializeComponent();


}
}

public class MyClass  : MainWindow

{
public RelayCommand<string> SearchedTextChanged { get; set; }  



 MyClass()
        {
            SearchedTextChanged = new RelayCommand<string>(OnSearchedTextChanged);
            DataContext=this;

        }

      private void OnSearchedTextChanged(string val)
        {
            if (val != null)
            {
                System.Diagnostics.Debug.WriteLine(val);
            }
        }


} 

MainWindow is the class which is derived from window.But it is not getting hit when the text changes in the textbox.However,if the above code is wriiten in mainwindow class,it works fine.Kindly help.

its a lot easier to simply bind to the Text property instead of using a trigger here. you just have to set the UpdateSourceTrigger to PropertyChanged. if you do so, every time you enter text in the textbox it will set the SearchText property in your viewmodel.

<TextBox Text="{Binding SearchText,UpdateSourceTrigger=PropertyChanged }"/>

viewmodel or something like that

public class SearchVM 
{
   private string searchtext;

   public string SearchText
   {
      get{return this.searchtext;} 
      set{this.seachtext = value; //INotifyPropertyChanged should be implemented to
         }
   }
}

mainwindow: you have to set the DataContext !

public partial class MainWindow: Window
{
    public MainWindow()
    {
      InitializeComponent();
      this.DataContext = new SearchVM();
    }
 }

code is handwritten but should take you in the right direction.

ps: please read about databinding, datacontext and MVVM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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