2012-02-14 57 views
0

我有以下XAML:WPF文本框觸發

<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> 

和代碼如下:

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); 
      } 
     } 


} 

主窗口是從window.But派生的類其當文本框中的文本發生變化時不會受到打擊。但是,如果上面的代碼在mainwindow類中運行,它可以正常工作。

回答

0

它更容易簡單地綁定到Text屬性,而不是在這裏使用觸發器。您只需將UpdateSourceTrigger設置爲PropertyChanged。如果你這樣做,每次你在文本框中輸入文本,它都會在你的viewmodel中設置SearchText屬性。

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

視圖模型或類似的

public class SearchVM 
{ 
    private string searchtext; 

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

主窗口的東西:你必須設置的DataContext

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

代碼是手寫的,但應該帶你進入正確的方向。

ps:請閱讀關於數據綁定,datacontext和MVVM