-1

I'm Coding windows 10 universal app. I Have a List box:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <TextBlock FontFamily="Segoe UI Symbol" Text="&#x26FD;" FontSize="25"/>
            <StackPanel Orientation="Vertical">
                <TextBlock Name="txtDate" Text="{Binding Date}" FontSize="15" Margin="20,0,0,0"/>
                <TextBlock Name="txtDitance" Text="{Binding Distance}" FontSize="15" Margin="20,5,0,0"/>
            </StackPanel>
            <TextBlock Name="txtPrice" Text="{Binding Price}" FontSize="15" Margin="30,0,0,0"/>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

When I click an item of the listbox, how do I can get the txtDate Text Value of that item? I need get txtDate Text Value of Selected Item as a String.

Jay Zuo
  • 15,653
  • 2
  • 25
  • 49
radin
  • 251
  • 3
  • 16

2 Answers2

0

I assumes when you click an item of listbox, you have handler defined for that. Now in handler,

private void handlr(object sender,SelectionChangedEventArgs e)
{
   var obj = e.OriginalSource.DataContext as YourBoundObjectType;
   // now do whatever you want with your obj
}
deeiip
  • 3,319
  • 2
  • 22
  • 33
0

You can use ListBox's SelectionChanged event and SelectedItem property to get the selected item. And since you used binding in your XAML, you can cast the selected item to your class to get the txtDate Text Value. For example:

In your XAML

<ListBox x:Name="MyListBox" SelectionChanged="MyListBox_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock FontFamily="Segoe UI Symbol" FontSize="25" Text="&#x26FD;" />
                <StackPanel Orientation="Vertical">
                    <TextBlock Name="txtDate" Margin="20,0,0,0" FontSize="15" Text="{Binding Date}" />
                    <TextBlock Name="txtDitance" Margin="20,5,0,0" FontSize="15" Text="{Binding Distance}" />
                </StackPanel>
                <TextBlock Name="txtPrice" Margin="30,0,0,0" FontSize="15" Text="{Binding Price}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And in your code-behind

private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //suppose MyClass is the class you used in binding
    var selected = MyListBox.SelectedItem as MyClass;
    //Date is the property you bind to txtDate
    string date = selected.Date.ToString();
}
Jay Zuo
  • 15,653
  • 2
  • 25
  • 49