【问题标题】:wpf-like trigger in code behind后面代码中的类似 wpf 的触发器
【发布时间】:2015-12-17 11:34:42
【问题描述】:

我正在使用 wpf 用 c# 编写一个简单的游戏。在我的 xaml.cs 中,我创建了一个完成所有工作的 Game 对象。

我需要能够在 Game 对象中的某个 propertyChange 上重新加载窗口。我的 xaml 中已经有了这个:

<TextBlock x:Name="PhaseTB" Text="{Binding Phase, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"/>

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

一切正常,文本框根据相位值更新。

我的问题是:当 Phase 值发生变化时,如何调用方法?文本更改得很好,但我不知道如何调用代码隐藏方法。

(对不起,菜鸟问题。我继承了代码,并不太了解整个事情是如何工作的)

【问题讨论】:

  • 在 Phase setter 中你可以调用你的方法...
  • @Pikoh 仅当方法是静态的(因为我要调用的方法在 MainWindow 类中并且我没有要引用的对象)

标签: c# wpf xaml


【解决方案1】:

您需要订阅活动PropertyChanged:

`<yourDataContext>`.PropertyChanged += propertyChangedHandler;

&lt;yourDataContext&gt; 是您的 DataContext,propertyChangedHandler 是事件处理程序。

注意 - 您可以像这样访问数据上下文:

((Game)textBox1.DataContext).PropertyChanged += propertyChangedHandler;

或

((Game)this.DataContext).PropertyChanged += propertyChangedHandler;

如果您的 TextBox 从 Window/Page 的主类继承 DataContext。

那个事件的存在正是为了你提到的目的。

至于这段代码应该放在哪里,我一般会把它放在构造函数中,因为它正在分配事件处理程序:

public class MainWindow() {
    public MainWindow() {
        InitializeComponent();
        // Here go the event handlers....
    }
}

更多信息:

【讨论】:

  • 该代码应该放在哪里?我的 textbox.DataContext 没有.PropertyChanged
  • 你需要投射它。等我更新答案。
  • @JohanHjalmarsson 包含phase 的类是什么?
  • 我会将游戏定义的重要部分添加到我的问题中
猜你喜欢
  • 2013-10-29
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
相关资源
最近更新 更多