创建自定义WPF事件 [英] Create custom wpf event

查看:322
本文介绍了创建自定义WPF事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个用于数据库连接的UserControl,其中用户输入了连接的用户名和密码。
此UserControl位于MainWindow.xaml

i've created an UserControl for Database connection where user input Username and Password for a connection. This UserControl is in a MainWindow.xaml

现在,在我的UserControl后面的代码中,我创建了MSSQL连接。如果登录成功,我想引发一个自定义事件以显示在MainWindow中。

Now, in code behind of my UserControl i create a MSSQL connection. If login Successfully, i want to Raise a custom event to expose in MainWindow.

例如在MyUserControl.xaml.cs

try
{

    using (SqlConnection sqlConn = new SqlConnection(connection))
    {
        sqlConn.Open();
        MessageBox.Show("Connessione Riuscita!", "Connessione a " + TextIP.Text, MessageBoxButton.OK, MessageBoxImage.Information);
        RaiseMyEvent();
        sqlConn.Close();                 
    }
}
catch (SqlException ex)
{
    MessageBox.Show("Connessione Fallita: " + ex.Message, "Connessione a " + TextIP.Text, MessageBoxButton.OK, MessageBoxImage.Error);
}

,在MainWindow.xaml中,我想使用mypersonalized事件:

<Window x:Class="XLogin.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:local="clr-namespace:XLogin" WindowStartupLocation="CenterScreen">
    <Grid>
        <local:DBLogin x:Name="DBLoginFrame" MyPersonalizedUCEvent="DBLoginFrame_MyPersonalizedUCEvent"/>
    </Grid>
</Window>

对于多类型连接(MSSQL,Oracle,MySql等),我需要此。

I need this for multiple type connection (MSSQL, Oracle, MySql etc).

如何获取?

推荐答案

首先,您应该定义一个委托,然后使用它

First you should define a delegate and then use that delegate to define that event.

在MyUserControl.xaml.cs文件中,添加以下内容

In your MyUserControl.xaml.cs file add the following

选项1

    public delegate void MyPersonalizedUCEventHandler(string sampleParam);

    public event MyPersonalizedUCEventHandler MyPersonalizedUCEvent;

    public void RaiseMyEvent()
    {
        // Your logic
        if (MyPersonalizedUCEvent != null)
        {
            MyPersonalizedUCEvent("sample parameter");
        }
    }

就是这样。您已经定义了事件。

And that's it. You have defined your event.

选项2

    public event Action<String> MyPersonalizedUCEvent;

    public void RaiseMyEvent()
    {
        // Your logic
        if (MyPersonalizedUCEvent != null)
        {
            MyPersonalizedUCEvent("sample parameter");
        }
    }

有关动作<的更多信息委托可以在此链接中找到。

More about the Action delegate can be found in this link.

注意:

在许多情况下,如果事件使用不当,它们可能导致内存泄漏。只需确保您已编写代码来删除已注册的事件处理程序,如下所示。

In many cases if events are not used properly they can cause memory leaks. Just make sure that you have written code to remove the registered event handlers as shown below.

        MyPersonalizedUCEvent -= MyPersonalizedUCEventHandler;

这篇关于创建自定义WPF事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆