2013-12-17 47 views
1

當我的keyword(字符串變量)的值發生變化時,我想調用VoiceSearch()方法。如何調用變量值更改的方法?

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(); 
    } 
} 
+0

擺脫那個try/catch塊。它什麼也沒做。 –

回答

6

最簡單的方式做,這是實現keyword作爲一個屬性:

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

這裏,_keyword是什麼是一個「釜底抽薪變量」簡稱。有一些接口,如INotifyPropertyChanged,它們在數據綁定中非常常用,值得研究,但在你的情況下,你必須編寫的最小代碼就是這個例子。

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

要麼宣佈keyword作爲屬性和調用的二傳手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()