Reputation: 3493
I'm writing a simple game in c# using wpf. In my xaml.cs I create a Game object that does all the work.
I need to be able to reload the window on a certain propertyChange in the Game object. I already have this in my xaml:
<TextBlock x:Name="PhaseTB" Text="{Binding Phase, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"/>
and Phase is part of the Game object:
public class Game : INotifyPropertyChanged
{
private static Game _instance;
private GamePhase phase;
public static Game Instance
{
get
{
if (_instance == null)
_instance = new Game(10, 10);
return _instance;
}
}
public GamePhase Phase
{
get { return phase; }
set
{
phase = value;
OnPropertyChanged("Phase");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
That all works fine and the textbox is updated according to the Phase value.
My question is: How do I call on a method whenever the Phase value changes? The text changes just fine, but I have no idea how to call a code-behind method.
(sorry for noob-question. I have inherited the code and don't really understand how the whole thing works)
Upvotes: 0
Views: 1219
Reputation: 6251
You need to subscribe to the event PropertyChanged
:
`<yourDataContext>`.PropertyChanged += propertyChangedHandler;
where <yourDataContext>
is your DataContext and propertyChangedHandler
is the event handler.
Note - You can access the Data Context like this:
((Game)textBox1.DataContext).PropertyChanged += propertyChangedHandler;
or
((Game)this.DataContext).PropertyChanged += propertyChangedHandler;
if your TextBox
inherits the DataContext from the Window/Page's main class.
That event exists precisely for the very purpose you mentioned.
And as for where this code should be put, I would generally put it in the constructor since it's assigning event handlers:
public class MainWindow() {
public MainWindow() {
InitializeComponent();
// Here go the event handlers....
}
}
More info:
Upvotes: 1