我被困住了。我正在尝试AddHandler
在 Page1 上设置一个按钮,这样当单击该按钮时,它将触发AddHandler
该MainWindow_MouseUp
事件,因此我可以单击 MainWindow 上的任何位置以显示一条消息。
我该如何解决这个问题?
笔记:
- 我已经在 MainWindow_load 事件中删除了 MainWindow_MouseUp 的处理程序,因此在 MainWindow 加载时不会显示该消息。
- 我有一个显示 Page1 的框架。
- 当点击 Page1 中的按钮时,它应该是 AddHandler,所以 MainWindow_MouseUp 会在 MainWindow 执行 MainWindow_MouseUp 事件时显示一条消息。
Page1.xaml
<Page x:Class="Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1" Background="Red">
<Grid>
<Button Content="AddHandler for MainWindow MouseUp message"
Height="42"
HorizontalAlignment="Left"
Margin="0,126,0,0"
Name="Button1"
VerticalAlignment="Top"
Width="300" />
<TextBlock Height="84"
HorizontalAlignment="Left"
Margin="80,184,0,0"
Name="TextBlock1"
Text="The button will add a handler in order to show a message on the MainWindow MouseUp event"
VerticalAlignment="Top"
Width="151"
TextWrapping="Wrap" />
<TextBlock Height="23"
HorizontalAlignment="Left"
Margin="12,56,0,0"
Name="TextBlock2"
Text="Page1"
VerticalAlignment="Top" />
</Grid>
</Page>
第1页.vb
Class Page1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs) _
Handles Button1.Click
Dim _MainWindow As New MainWindow
AddHandler _MainWindow.MouseUp, AddressOf Button1_Click
End Sub
End Class
主窗口.xaml
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Frame Source="Page1.xaml"
Height="300"
HorizontalAlignment="Left"
Margin="110,-1,0,0"
Name="Frame1"
VerticalAlignment="Top"
Width="300" />
<TextBlock Height="144"
HorizontalAlignment="Left"
Margin="0,48,0,0"
Name="TextBlock2"
Text="Click here to show a message if handler MainWindow MouseUp is added from page1"
VerticalAlignment="Top"
TextWrapping="Wrap"
Width="104"
Foreground="#FF003AFF" />
<TextBlock Height="153"
HorizontalAlignment="Left"
Margin="416,159,0,0"
Name="TextBlock3"
Text="Click here to show a message if handler MainWindow MouseUp is added from page1"
VerticalAlignment="Top"
TextWrapping="Wrap"
Foreground="#FFEF00FF" />
</Grid>
</Window>
主窗口.vb
Public Class MainWindow
Private Sub Window_Loaded(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs) _
Handles MyBase.Loaded
RemoveHandler Me.MouseUp, AddressOf MainWindow_MouseUp
End Sub
Private Sub MainWindow_MouseUp(ByVal sender As Object, _
ByVal e As MouseEventArgs) _
Handles Me.MouseUp
Test1()
End Sub
Public Sub Test1()
MessageBox.Show("AddHandler added from page 1 was successful!")
End Sub
End Class