[英]WPF UserControl Child Component Event Handler
I have a UserControl that contain let's say a button (or any other object).我有一个 UserControl,其中包含一个按钮(或任何其他对象)。
<UserControl x:Class="StackOverFlowQuestion.UserControlButton"
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:StackOverFlowQuestion"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button
x:Name="Button1"
Content="Click me for testing"/>
</Grid>
</UserControl>
and I want to access that Button's(Or any Object) Click Event or any Event form the parent that contains the UserControl.并且我想访问该按钮的(或任何对象)单击事件或包含 UserControl 的父级的任何事件。
<Window x:Class="StackOverFlowQuestion.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:StackOverFlowQuestion"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:UserControlButton/>
</Grid>
</Window>
Thanks.谢谢。
It's quite easy.这很容易。 Just put a public event to the
UserControl
(code behind) for it could be accessible from outside of UserControl and do forward the Click event from your button.只需将公共事件放入
UserControl
(代码隐藏),因为它可以从 UserControl 外部访问,并从您的按钮转发 Click 事件。
public partial class UserControlButton : UserControl
{
public event RoutedEventHandler ButtonClick;
private void UsrCtlButton_Click(object sender, RoutedEventArgs e)
{
ButtonClick?.Invoke(sender, e);
}
}
XAML of UserControl
: UserControl
XAML :
<Button x:Name="Button1" Content="Click me for testing" Click="UsrCtlButton_Click"/>
XAML where UserControl
being used:使用
UserControl
XAML:
<local:UserControlButton ButtonClick="Some_event_handler_to_handle_Button_Click"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.