【发布时间】:2020-03-24 11:04:03
【问题描述】:
我有一个包含按钮(或任何其他对象)的 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>
并且我想访问该按钮的(或任何对象)单击事件或包含 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>
谢谢。
【问题讨论】:
-
如何以及从哪里访问它? XAML?还是代码?
-
访问它是从xaml代码中添加事件处理程序的意思
-
无法从窗口的 XAML 标记中将事件处理程序连接到在
UserControl中定义的Button。然后,您需要在UserControl类中定义一个事件。 -
这正是我所做的,非常感谢。