我写了个很简单的用户控件(UserControl),一个带 “❌” 按钮(用于清除内容)的文本框:
有一个很严重的问题,点击 “❌” 按钮没有任何响应,设置断点后发现事件根本就没有被执行。
<UserControl x:Class="xxx"
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:local="clr-namespace:xxx.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="24"
d:DesignWidth="100"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
mc:Ignorable="d">
<Grid>
<TextBox x:Name="tbInput" />
<Button x:Name="btnClear"
Width="{Binding ActualHeight, Mode=OneWay, RelativeSource={RelativeSource Self}}"
HorizontalAlignment="Right"
Background="#7FDDDDDD"
BorderBrush="{x:Null}"
Click="BtnClear_Click"
Content="❌"
Foreground="#7F000000" />
</Grid>
</UserControl>
using System.Windows;
using System.Windows.Controls;
namespace xxx
{
public partial class xxx : UserControl
{
public xxx()
{
InitializeComponent();
}
private void BtnClear_Click(object sender, RoutedEventArgs e)
{
tbInput.Clear();
}
}
}
天呐,我好蠢,新建了个项目用该控件发现没问题,把该控件用在同项目不同位置也没问题,我就纳了闷,原来是按钮和其他控件重叠了(视觉上未重叠),所以才无法触发点击事件,当然这其中的内在原因不知道。