Reputation: 4572
I want invoke VoiceSearch()
method when a value of my keyword
(string variable) change.
private void VoiceSearch()
{
try
{
query.Append(keyword);
Browser.Navigate(query.ToString());
}
catch (Exception)
{
throw;
}
}
solution
private string _keyword
public string keyword
{
get
{
return _keyword;
}
set
{
_keyword=value;
VoiceSearch();
}
}
Upvotes: 3
Views: 1457
Reputation: 2346
Simplest way to do this is implement keyword
as a property:
private string _keyword
public string keyword
{
get
{
return _keyword;
}
set
{
_keyword=value;
VoiceSearch();
}
}
Here, _keyword
is what is referred to as a "backing variable". There are interfaces such as INotifyPropertyChanged
which are very commonly used in databinding that are worth looking into, but in your case, the minimum code you have to write is this example.
Upvotes: 6
Reputation: 12616
Either declare keyword
as a property and invoke VoiceSearch
in the setter or create a special method for setting the keyword
and invoke VoiceSearch
from it when called.
Property
private string keyword;
public string Keyword
{
get { return keyword; }
set { keyword = value; VoiceSearch(); }
}
Method
public void SetKeyword(string value)
{
keyword = value;
VoiceSearch();
}
Assuming that keyword
is actually string
. These two options still leaves you with a chance to change the variable and not call VoiceSearch()
.
Upvotes: 2
Reputation:
You should look into INotifyPropertyChanged. Instead of variable I would suggest to use property. See a MSDN example below:
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));
}
}
}
}
Upvotes: 0