sitaramaraju
sitaramaraju

Reputation: 71

How to add hyperlinkbuttons dynamically from c# codebehind to a stackpanel present in the listbox?

Hi i have a requirement i need your help for it:-

I have a set of phone numbers of type string separated by a comma , now i want to assign each phone number to hyperlink and on click of it will invoke the PhoneCallTask and make a call to that particular phone number.

1) So , how to assign each phone number to a hyperlink(should we dynamically generate the hyperlink? in c# codebehind)

2)if so , how to dynamically generate hyperlink buttons and add it to a stack panel present in a listbox ?

3)How would i know which Hyperlinkbutton is clicked?

4)All HyperlinkButton's would point to same hyperlink click event?

Thanks in Advance.

Upvotes: 0

Views: 1282

Answers (1)

Pedro Lamas
Pedro Lamas

Reputation: 7243

In your MainPage.xaml, add this inside the ContentPanel control:

<ListBox x:Name="PhoneNumbersList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <HyperlinkButton Content="{Binding}" Click="PhoneNumberHyperlinkButton_Click" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Then, on the MainPage code behind, add this code:

public MainPage()
{
    InitializeComponent();

    var phoneNumbers = new string[] { "9999999", "8888888", "7777777" };

    PhoneNumbersList.ItemsSource = phoneNumbers;
}

private void PhoneNumberHyperlinkButton_Click(object sender, RoutedEventArgs e)
{
    var phoneNumberHyperlinkButton = (HyperlinkButton)sender;

    var phoneNumber = (string)phoneNumberHyperlinkButton.Content;

    new Microsoft.Phone.Tasks.PhoneCallTask()
    {
        PhoneNumber = phoneNumber
    }.Show();
}

That's it!

Upvotes: 3

Related Questions