如何在变量的值变化上调用方法?

时间:2013-12-17 12:12:29

标签: c# listener invoke

当my VoiceSearch()(字符串变量)的值发生变化时,我想调用keyword方法。

private void VoiceSearch()
    {
        try
        {
            query.Append(keyword);

            Browser.Navigate(query.ToString());

        }
        catch (Exception)
        {
            throw;
        }
    }

溶液

private string _keyword
public string keyword
{
  get
  { 
    return _keyword;
  }
  set
  {
    _keyword=value;
    VoiceSearch();
  }
}

3 个答案:

答案 0 :(得分:6)

最简单的方法是将keyword实现为属性:

private string _keyword
public string keyword
{
  get
  { 
    return _keyword;
  }
  set
  {
    _keyword=value;
    VoiceSearch();
  }
}

这里,_keyword是所谓的“支持变量”。有一些接口,例如INotifyPropertyChanged,它们在数据绑定中非常常用,值得研究,但在你的情况下,你必须编写的最小代码就是这个例子。

答案 1 :(得分:1)

keyword声明为属性并在setter中调用VoiceSearch,或者在调用时创建一个特殊方法来设置keyword并从中调用VoiceSearch

<强>属性

private string keyword;
public string Keyword
{
    get { return keyword; }
    set { keyword = value; VoiceSearch(); }
}

方式

public void SetKeyword(string value)
{
    keyword = value;
    VoiceSearch();
}

假设keyword实际上是string。这两个选项仍然让您有机会更改变量,而不是调用VoiceSearch()

答案 2 :(得分:0)

您应该查看INotifyPropertyChanged。而不是变量我会建议使用属性。请参阅下面的MSDN示例:

using System.ComponentModel;

namespace SDKSample
{
  // This class implements INotifyPropertyChanged 
  // to support one-way and two-way bindings 
  // (such that the UI element updates when the source 
  // has been changed dynamically) 
  public class Person : INotifyPropertyChanged
  {
      private string name;
      // Declare the event 
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }

      public Person(string value)
      {
          this.name = value;
      }

      public string PersonName
      {
          get { return name; }
          set
          {
              name = value;
              // Call OnPropertyChanged whenever the property is updated
              OnPropertyChanged("PersonName");
          }
      }

      // Create the OnPropertyChanged method to raise the event 
      protected void OnPropertyChanged(string name)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
  }
}