[英]Executing a method in parent user control from a child in WPF
I have a user control named Display
in MainWindow.xaml
. 我在
MainWindow.xaml
有一个名为Display
的用户控件。 Display
user control itself has a custom class Workspace.cs
in it like this: Display
用户控件本身具有一个自定义类Workspace.cs
,如下所示:
<UserControl x:Class="Program.Main.Controls.Display.Display"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:workspaces="clr-namespace:Program.Workspaces">
<Border>
<Grid>
<workspaces:Workspace x:Name="MyWorkspace" ClipToBounds="True"/>
</Grid>
</Border>
</UserControl>
In my custom class that is Worskspace.cs
I'm rising a MouseLeftButtonDown
event, I want to execute the ThisCommandCameFromWorkspace
method in Display.xaml.cs
when rising this event. 在我的自定义类
Worskspace.cs
,正在Worskspace.cs
MouseLeftButtonDown
事件,在ThisCommandCameFromWorkspace
此事件时,我想在Display.xaml.cs
执行ThisCommandCameFromWorkspace
方法。
What is the best approach to do this? 最好的方法是什么? And What is the easiest?
最简单的是什么?
Updated: 更新:
In my Workspace.cs I have 在我的Workspace.cs中,
public event Action MyEventHandler;
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (MyEventHandler!= null)
MyEventHandler();
}
Now I want to capture this in Display
user control and execute a method of its code-behind. 现在,我想在“
Display
用户控件中捕获它并执行其代码隐藏的方法。
I'd suggest not to use Action
as event delegate type, but instead use the common type EventHandler
. 我建议不要使用
Action
作为事件委托类型,而应使用通用类型EventHandler
。 And don't call it MyEventHandler
as it is not a handler, but just the event: 并且不要将其
MyEventHandler
因为它不是处理程序,而只是事件:
public event EventHandler MyEvent;
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (MyEvent != null)
{
MyEvent(this, EventArgs.Empty);
}
}
Now you would easily attach a handler for the event in the Display's XAML (supported by Intellisense in Visual Studio): 现在,您可以轻松地在Display的XAML中附加事件的处理程序(由Visual Studio中的Intellisense支持):
<workspaces:Workspace ... MyEvent="Display_MyEvent"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.