[英]wpf-like trigger in code behind
I'm writing a simple game in c# using wpf. 我正在使用wpf在C#中编写一个简单的游戏。 In my xaml.cs I create a Game object that does all the work. 在我的xaml.cs中,我创建了一个Game对象,可以完成所有工作。
I need to be able to reload the window on a certain propertyChange in the Game object. 我需要能够在Game对象中的某个propertyChange上重新加载窗口。 I already have this in my xaml: 我的xaml中已经有这个了:
<TextBlock x:Name="PhaseTB" Text="{Binding Phase, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"/>
and Phase is part of the Game object: 而Phase是Game对象的一部分:
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) (对不起的问题,很抱歉。我已经继承了代码,还不太了解整个过程如何工作)
You need to subscribe to the event PropertyChanged
: 您需要订阅事件PropertyChanged
:
`<yourDataContext>`.PropertyChanged += propertyChangedHandler;
where <yourDataContext>
is your DataContext and propertyChangedHandler
is the event handler. 其中<yourDataContext>
是您的DataContext, propertyChangedHandler
是事件处理程序。
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. 如果您的TextBox
从Window / Page的主类继承了DataContext。
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: 更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.