编写可以在c# WPF中所有自定义控件中共享的事件
本文关键字:自定义控件 共享 事件 WPF | 更新日期: 2023-09-27 18:12:20
我有多个自定义控件,我注意到它们都共享相同的事件(自定义)示例:OnMoved等
我现在要做的是,复制&将相同的代码从一个控件粘贴到另一个控件。
所以,无论如何我都可以编写自定义事件,可以在c# WPF中共享所有控件吗?
我在所有控件中使用的事件示例:
Point lastPosition = new Point();
Point currentPosition = new Point();
public static void OnMoved(object sender, EventArgs e)
{
currentPosition.X = Canvas.GetLeft(explorer);
currentPosition.Y = Canvas.GetTop(explorer);
// didn't moved
if (currentPosition.X == lastPosition.X || currentPosition.Y == lastPosition.Y)
{
return;
}
lastPosition.X = Canvas.GetLeft(explorer);
lastPosition.Y = Canvas.GetTop(explorer);
}
这取决于您需要事件做什么,但是您可以将事件放入共享类中:
public class MyEvents
{
public static void SomeEvent(object sender, EventArgs e)
{
MessageBox.Show("hi");
}
}
然后在你需要的地方订阅它:
SomeButton.Click += MyEvents.SomeEvent;
您可以创建具有公共虚拟事件的基类,并且该事件将出现在从基类派生的任何类中。这将使您不必一遍又一遍地复制粘贴相同的代码。
你可以!你唯一需要带在身边的东西是:
->相同事件(事件的参数必须完全相同。->他们也会做同样的事。
不好的是你不能把控件和事件混在一起。例如,你可以为一个按钮创建一个。click事件,这样它就会关闭你的应用程序,但是如果你希望在按"F8"键时也这样做,它将不起作用,因为event参数是不同的~
你可以尝试在所有事件中使用相同的方法。例子:
private void _Close()
{
Process.GetCurrentProcess().Close();
}
您可以在表单中按下"F5"键或在文本框中单击按钮或键入"关闭"键来关闭。
button.Click += Button_Close;
private void Button_Close(Object o, RoutedEventArgs e)
{
_Close();
}
this.KeyDown += This_Close;
private void This_Close(Object o, KeyEventArgs e)
{
if(e.KeyCode == Key.F5) _Close();
}
TextBox.TextChanged += Text_Close;
private void Text_Close(Object o, TextChangedEventArgs e)
{
if(TextBox.Text == "Close") _Close();
}