Playlist MyTV untuk smart TV berserta intisari rancangan bermula RM4.99 sebulan. Selanjutnya →

Create event based component in C#

Sabtu, 10 Mei 2014, 8:20 pm0

This post is about how to create event based component in C# for Windows Phone. Assuming that we have XAML class that interact with data model component, we’re using event to pass the data around.

In model class, create delegate and event property. Delegate is property that define the signature of callback, and event is property that other class can hook their callback to.

If you want to pass additional parameters in event handler, declare a new event argument class that extend EventArgs and assign the values when raising the event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class DataLoadedEventArgs : EventArgs
{
    public int TotalRows { get; set; }
}
 
public class DataSource
{
    public delegate void DataLoadedEventHandler(object sender, DataLoadedEventArgs e);
    public delegate void DataErrorEventHandler(object sender, EventArgs e);
 
    public event DataLoadedEventHandler DataLoaded;
    public event DataErrorEventHandler DataError;
 
    public void GetDataFromServer()
    {
        // code for getting data
 
        // this is how to raise the event
        if (DataLoaded != null)
        {
            DataLoaded(this, new DataLoadedEventArgs()
            {
                TotalRows = 20
            });
        }
<div id="aff_off"></div>
 
 
        // if has error, raise another event
        if (DataError != null)
        {
            DataError(this, new EventArgs());
        }
    }
}

Then in XAML class attach the callback to listen for the event raised from the model class, and make sure to detach the event when not used anymore.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public partial class MainPage : PhoneApplicationPage
{
    private DataSource dataSource;
 
    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        dataSource = new DataSource();
        dataSource.DataLoaded += dataSource_DataLoaded;
        dataSource.DataError += dataSource_DataError;
    }
 
    private void MainPage_Unloaded(object sender, RoutedEventArgs e)
    {
        dataSource.DataLoaded -= dataSource_DataLoaded;
        dataSource.DataError -= dataSource_DataError;
    }
 
    private void dataSource_DataLoaded(object sender, DataLoadedEventArgs e)
    {
        // use e.TotalRows
    }
 
    private void dataSource_DataError(object sender, EventArgs e)
    {
        // ...
    }
}

Tulis komen: