Passing c# ListBox Item to method

660 Views Asked by At

Small programming problem here, hopefully someone can point me in the right direction.

Im using a list here on a WP7 page. (Silverlight ListBox).

My list is populated by an XML file. Each List item has three text boxes populated as per the code below.

I need to pass one of the selected ListBox items as text to the following method to poulate the phone number.

This is my c# code which populates the listbox, and then the phonecall method.

private void planning(object sender, ManipulationStartedEventArgs e)
    {
        XElement _xml = XElement.Load("contacts/contacts.xml");
           {
            contacts.Items.Clear();
            foreach (XElement value in _xml.Elements("channel").Elements("item"))
            {
                ContactsItem _item = new ContactsItem();
                _item.Title = value.Element("title").Value;
                _item.Web = value.Element("web").Value;
                _item.Phone = value.Element("phone").Value;

                contacts.Items.Add(_item);
             }
           }

    }

  private void phone_number(object sender, MouseButtonEventArgs e)
    {

        Microsoft.Phone.Tasks.PhoneCallTask phonecall = new Microsoft.Phone.Tasks.PhoneCallTask();
        phonecall.PhoneNumber = //value here
        phonecall.Show();

    }

With my accompanying class:

 public class ContactsItem
{
    private string _title;
    private string _web;
    private string _phone;

    public string Title
    {
        get { return _title; }
        set { _title = value; }
    }
//etc etc....

The idea is, when you click on the binded 'Phone' text in the list box, it will pass that value to the phonecall method. When the text box with the phone number is clicked, it calls that phone_number method.

Hope you understand. Many thanks.

2

There are 2 best solutions below

0
On

Look into the sender's DataContext property (you may have to do some type casting) in the phonecall method (I mean the handler which handles the ListBoxItem's click event). If the ListBox is bound correctly, the ContactsItem will be the menu item's DataContext.

Also, as a side note: Learn to follow .NET's naming standards (CamelCase for methods), it will make your life much easier in the long run, especially if you were to collaborate with other propgrammers.

And you can use this to generate simple properties with basic getters/setters:

public string Name {get; private set;}
2
On

Assuming "contacts" is your ListBox, you could get the phone number by doing

((ContactsItem)contacts.SelectedItem).Phone