当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();
}
}
答案 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));
}
}
}
}