如果我有UserControl
<UserControl
x:Class="UserInterface.AControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Button
Content="Set"
Name="setButton" />
</Grid>
</UserControl>
如何在使用此控件时为setButton
外部分配事件处理程序?
<UserControl
xmlns:my="clr-namespace:UserInterface"
x:Class="UserInterface.AnotherControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<my:AControl />
</Grid>
</UserControl>
我可以使用类似的东西吗?
<my:AControl
setButton.Click="setButton_Click" />
答案 0 :(得分:3)
你无法真正做到这一点,但你可以做的是在你的自定义UserControl(AControl)中,从它公开一个公共事件“SetButtonClicked”,然后订阅它。这假设在AControl上存在SetButton。
例如,AControl的C#代码将变为
public class AControl : UserControl
{
public event EventHandler<EventArgs> SetButtonClicked;
public AControl ()
{
InitializeComponent();
this.setButton.Click += (s,e) => OnSetButtonClicked;
}
protected virtual void OnSetButtonClicked()
{
var handler = SetButtonClicked;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
并且在Xaml中你会订阅如下
<my:AControl SetButtonClick="setbutton_Clicked"/>
编辑:我会问你在这里尝试的是什么。如果你想在AControl之外处理一些额外的行为,那么可能会把事件称为其他东西?例如,您是否只想通知某人点击了按钮,或者操作是否已完成?通过在AControl中封装您的自定义行为,您可以暴露AControl的消费者真正关心的行为。 最好的问候,