Razor Razor - 2 months ago 14
C# Question

Apply a routed event handler to an application bar button

I am trying to assign a routed event handler to a method that contains routed event arguments. I am constantly receiving this error:


Cannot implicitly convert type 'System.Windows.RoutedEventHandler' to 'System.EventHandler'


Here is the function:

private void lists_AddListButton_Click(object sender, RoutedEventArgs e)
{
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (Stream stream = storage.CreateFile("list.xml"))
{
XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("lists", new XElement("list", new XElement("name", "random list"), new XElement("date", DateTime.Now.ToString()))));
document.Save(stream);

var items = (from query in document.Descendants("list")
select new ListsXmlBinder
{
Name = query.Element("name").Value,
Date = query.Element("date").Value
}).ToList();

lists_ListViewer.ItemsSource = items;
}
}
}


Here is where I am trying to assign the event handler:

private void BuildLocalizedApplicationBar()
{
// Set the page's ApplicationBar to a new instance of ApplicationBar.
ApplicationBar = new ApplicationBar();

// Create a new button and set the text value to the localized string from AppResources.
ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
appBarButton.Text = AppResources.AppBarButtonText;
appBarButton.Click += new RoutedEventHandler(lists_AddListButton_Click);
ApplicationBar.Buttons.Add(appBarButton);

// Create a new menu item with the localized string from AppResources.
ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
ApplicationBar.MenuItems.Add(appBarMenuItem);
}


The event handler is where the new
RoutedEventHandler
part is. Any suggestions on how to solve this problem?

Answer

I guess, ApplicationBarIconButton.Click is EventHandler, not RoutedEventHandler. So try to change

appBarButton.Click += new RoutedEventHandler(lists_AddListButton_Click);

to

appBarButton.Click += new EventHandler(lists_AddListButton_Click);

or just

appBarButton.Click += lists_AddListButton_Click;

as Jogy recommends

and

void lists_AddListButton_Click(object sender, RoutedEventArgs e)

to

void lists_AddListButton_Click(object sender, EventArgs e)