我试图了解一个简单的 WPF 应用程序中的 RoutedEventArgs.Source 属性。这是 XAML 代码
<Window x:Class="BubbleDemo.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">
<StackPanel x:Name="stackPanel1" Button.Click="OnOuterButtonClick">
<Button x:Name="button1" Content="Button 1" Margin="5" />
<Button x:Name="button2" Margin="5" Click="OnButton2">
<ListBox x:Name="listBox1">
<Button x:Name="innerButton1" Content="Inner Button 1" Margin="4" Padding="4" Click="OnInner1" />
<Button x:Name="innerButton2" Content="Inner Button 2" Margin="4" Padding="4" Click="OnInner2" />
</ListBox>
</Button>
<ListBox ItemsSource="{Binding}" />
</StackPanel>
</Window>
这是背后的代码
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace BubbleDemo
{
public partial class MainWindow : Window
{
private ObservableCollection<string> messages = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
this.DataContext = messages;
}
private void AddMessage(string message, object sender, RoutedEventArgs e)
{
messages.Add(String.Format("{0}, sender: {1}; source: {2}; original source: {3}",
message, (sender as FrameworkElement).Name,
(e.Source as FrameworkElement).Name,
(e.OriginalSource as FrameworkElement).Name));
}
private void OnOuterButtonClick(object sender, RoutedEventArgs e)
{
AddMessage("outer event", sender, e);
}
private void OnInner1(object sender, RoutedEventArgs e)
{
AddMessage("inner1", sender, e);
}
private void OnInner2(object sender, RoutedEventArgs e)
{
AddMessage("inner2", sender, e);
e.Handled = true;
}
private void OnButton2(object sender, RoutedEventArgs e)
{
AddMessage("button2", sender, e);
e.Source = sender;
}
}
}
当我单击 InnerButton1 时,会引发单击事件,然后执行 OnInner1 处理程序。After 执行 OnButton2 处理程序,它使用sender参数设置 RoutedEventArgs.Source 属性。如果您构建并执行此代码,您可以看到输出结果。当事件到达 OnOuterButtonClick 处理程序时,底部 ListBox 中的输出应为:
inner1,发件人:innerButton1;来源:innerButton1;原始来源:innerButton1
button2,发送者:button2;来源:innerButton1;原始来源:innerButton1
外部事件,发送者:stackPanel1;来源:按钮2;原始来源:innerButton1
但输出是这样的
inner1,发件人:innerButton1;来源:innerButton1;原始来源:innerButton1
button2,发送者:button2;来源:innerButton1;原始来源:innerButton1
外部事件,发送者:stackPanel1;来源:innerButton1;原始来源:innerButton1
在 OnButton2 处理程序中重新分配的 RoutedEventArgs.Source 属性已更改,但会返回到 OnOuterButtonClick 处理程序内的引用 innerButton1。
为什么会发生这种情况?谢谢