在父控件中处理PreviewMouseDown-Event后,WPF切换按钮不切换
本文关键字:WPF 按钮 控件 处理 PreviewMouseDown-Event | 更新日期: 2023-09-27 18:17:57
如果您处理UserControl
的PreviewMouseDown
事件,并且UserControl
内部是ToggleButton
,则它不会触发内置的本机检查事件,也不会触发单击事件(蓝色突出显示)。如果你不处理预览事件,它可以正常工作。
我认为预览事件不会将事件标记为已处理,但即使使用
e.handled = false;
之后将没有click或checked事件。
如何启用切换按钮的点击和检查事件?
理解问题的代码:
WpfApplication1.cs
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void UserControl1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//working
MessageBox.Show("Preview down");
e.Handled = false; //this is what I tried
}
private void UserControl1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//working
MessageBox.Show("preview up");
}
}
}
WpfApplication。Xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:UserControl1 PreviewMouseLeftButtonDown="UserControl1_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="UserControl1_PreviewMouseLeftButtonUp" ></local:UserControl1>
</Grid>
</Window>
UserControl1.cs:
namespace WpfApplication1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void ToggleButton_Checked(object sender, RoutedEventArgs e)
{
//Not called
MessageBox.Show("test");
}
private void ToggleButton_Click(object sender, RoutedEventArgs e)
{
//not called
MessageBox.Show("test");
}
}
}
UserControl1.xaml
<UserControl x:Class="WpfApplication1.UserControl1"
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"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ToggleButton Checked="ToggleButton_Checked" Click="ToggleButton_Click"></ToggleButton>
</Grid>
</UserControl>
当用户控件中的事件被触发时,需要为用户控件引发事件处理程序。这将向上传递,并处理来自两者的偶数。
点击ToggleButton
,触发ToggleButton_Click
,触发UserControl1_PreviousMouseLeftButtonDown
事件。
WpfApplication1
UserControl1.ToggleButtonClick += new EventHandler(UserControl1_PreviewMouseLeftButtonDown);
private void UserControl1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Preview down");
// Handle the event
}
UserControl1
public event EventHandler ToggleButtonClick;
private void ToggleButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("test");
// Handle the event
}