繁体   English   中英

WPF文本框触发器

[英]WPF TextBox Trigger

我有以下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>

代码如下:

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是派生自window的类。但是当文本在文本框中更改时不会被击中。但是,如果上面的代码在mainwindow类中被写入,则可以正常工作。请提供帮助。

只需将其绑定到Text属性,而不是在此处使用触发器,将容易得多。 您只需要将UpdateSourceTrigger设置为PropertyChanged。 如果这样做,则每次在文本框中输入文本时,都会在视图模型中设置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
         }
   }
}

mainwindow:您必须设置DataContext

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

代码是手写的,但应该为您提供正确的方向。

ps:请阅读有关数据绑定,datacontext和MVVM的信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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