paddy
paddy

Reputation: 165

How to get the ListBox' tapped item to print it somewhere else?

I show file's lines in my ListBox. I need to grab the line that is tapped by user and show it as the Button's Content.

I did something like this:

void OnItemTapped(object sender, TappedRoutedEventArgs args)
{
    firstElement.Content = itemsControl.SelectedItem.ToString();
}

In xaml I have:

<Button Name="firstElement"                
        Content="{Binding}"
        Grid.Row="1" Grid.Column="0"
        Tapped="OnItemTapped" />

This way OnItemTapped sends data to my Button.

The data is pulled from:

<ListBox x:Name="itemsControl"
         ItemsSource="{Binding}"
         FontSize="24"
         Width="1100"
         HorizontalAlignment="Center">

The problem is that instead of data shown correctly within ListBox I get MyNamespace.ItemsData which is class's address, where I keep strings from splitted ListBox line( I show each line in 5 TextBlocks - one for each word).

public class ItemsData
{
    public string value0 { get; set; }
    public string value1 { get; set; }
    public string value2 { get; set; }
    public string value3 { get; set; }
    public string value4 { get; set; }
}

Upvotes: 1

Views: 216

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39966

You need to cast to your Model first then select what property you need to show. Like this:

firstElement.Content = (itemsControl.SelectedItem as ItemsData).value0;

Based on your design to get all properties you can do like this:

var x = (itemsControl.SelectedItem as ItemsData);
firstElement.Content = string.Format("{0},{1},{2},{3},{4}" , x.value0 , x.value1 , x.value2 , x.value3 , x.value4);

And in C#6 you could:

firstElement.Content = string.Format($"{x.value0},{x.value1},{x.value2},{x.value3},{x.value4}");

Upvotes: 2

AlexDrenea
AlexDrenea

Reputation: 8039

You can use the ElementName binding:

<Button Name="firstElement"                
        Content="{Binding ElementName=itemsControl, Path=SelectedItem}"
        Grid.Row="1" Grid.Column="0"/>

But because SelectedItem is a ItemsClass instance you need to override its ToString() method to get the text you need:

public class ItemsData
{
    public string value0 { get; set; }
    public string value1 { get; set; }
    public string value2 { get; set; }
    public string value3 { get; set; }
    public string value4 { get; set; }

    public string AllValues 
    {
        get 
        {
            return $"{value0} {value1} {value2} {value3} {value4}";
        }
    }

    public override string ToString()
    {
        return AllValues;
    }
}

Check this great document for an extensive list of binding properties.

*Note: Your list will handle all the selection display and highlights so at least for that, you don't need to use the Tapped event.

Upvotes: 0

Related Questions