Skip to main content
 首页 » 编程设计

c#之事件识别 C# WPF

2024年02月05日11pander-it

我遇到了事件问题。我得到了一个看起来像这样的第一个窗口:

using System.Windows; 
 
namespace EventsTests 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
        public MainWindow() 
        { 
            InitializeComponent(); 
            /*Binding Event to MainWindow 
              dont work until you will help*/ 
            MainWindow mw = new MainWindow(); 
            mw.RaiseEvent += raiseEvent_EventHandler; 
        } 
        public void raiseEvent_EventHandler() 
        { 
             MessageBox.Show("MAINWINDOW Event Fired"); 
        } 
 
        private void Button_Click(object sender, RoutedEventArgs e) 
        { 
             SecondPage sp = new SecondPage(); 
             sp.Show(); 
        } 
    } 
} 

现在第二个页面做的不是很多:

using System.Windows; 
 
namespace EventsTests 
{ 
    /// <summary> 
    /// Interaction logic for SecondPage.xaml 
    /// </summary> 
    public partial class SecondPage : Window 
    { 
        SecondPageViewModel spvm = new SecondPageViewModel(); 
        public SecondPage() 
        { 
            this.DataContext = spvm; 
            InitializeComponent(); 
        } 
 
        private void Button_Click(object sender, RoutedEventArgs e) 
        { 
            spvm.raiseEventActivate(); 
        } 
    } 
} 

最后我有了 SecondPageViewModel:

namespace EventsTests 
{ 
    public delegate void raiseEventEventHandler(); 
 
    class SecondPageViewModel  
    { 
        public event raiseEventEventHandler raiseEvent; 
        public void raiseEventActivate() 
        { 
            if(raiseEvent != null) 
            { 
                raiseEvent(); 
            } 
        } 
    } 
} 

现在我想,当我单击第二页上的按钮时,将触发事件并且 MainWindow 会识别该事件。 使用此代码我得到错误:

错误 1 ​​无法分配给“RaiseEvent”,因为它是“方法组”

有人可以帮助我吗?或者举个例子?

感谢每一个提示;)

请您参考如下方法:

RaiseEvent不是您的事件,它是 Window 的一种方法。

我想你想这样做:

SecondPage sp = new SecondPage(); 
sp.raiseEvent += raiseEvent_EventHandler;     
sp.Show(); 

即向第二个页面事件注册一个事件处理器。

尽管我不提倡为此使用事件 处理程序。虽然我不知道您想要实现什么,但我宁愿做一些事情,比如将 ViewModel 对象传递给 SecondPage,这样主窗口就可以响应该 ViewModel 的状态变化。

在 WPF 中,我始终以零代码为目标。

作为对讨论的回应,一个虚拟机如何引用另一个虚拟机。首先传入虚拟机:

SecondPageViewModel spvm; 
public SecondPage(SecondPageViewModel model) 
{ 
    spvm = model; 
    this.DataContext = spvm; 
    InitializeComponent(); 
} 

然后 SecondpageVM 将 MainVM 作为构造函数中的参数:

SecondPage sp = new SecondPage(new SecondPageViewModel(mainVM)); 

对主模型的更新是在 SecondPageViewModel 中完成的。第二页本身没有对它的引用。

ThirdPage tp = new ThirdPage(new ThirdPageViewModel(spvm)) 

第三页虚拟机可以通过第二页虚拟机的属性访问主页面虚拟机:spvm.MainVm