How to get text from textBlock during SelectionChangeEvent from a ListBox?

耗尽温柔 提交于 2019-12-13 04:46:07

问题


I am try to get a text from my TextBlock during item select from my Listbox.

Here is my code for listbox in my xaml file..

<ListBox x:Name="listBox" Height="535" Margin="7,0,12,0" 
      SelectionChanged="selectedItem" 
      ItemsSource="{Binding}">

    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <toolkit:WrapPanel FlowDirection="LeftToRight" 
                ItemWidth="215" ItemHeight="215" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate x:Uid="info">
        <DataTemplate>
            <StackPanel>
                <Border>
                    <Image HorizontalAlignment="Left" Margin="6,6,0,0" 
                        Name="image1" Stretch="Fill" 
                        VerticalAlignment="Top" 
                        Source="{Binding imageSource}" />
                </Border>
                <TextBlock x:Name="path" Foreground="Transparent" 
                    Text="{Binding imagePath}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>

</ListBox>

For my c# code i am using a selectionChangedEvent method that will handle tap event but i can not figure out how to get content of my TextBlock element.

private void selectedItem(object sender, SelectionChangedEventArgs e)
{
    //I need to take the content of my textblock w/c carry the path for
    //my image to be use to share using ShareMediaTask.    
    //path = the content of my textblock

    var task = new ShareMediaTask();
    task.FilePath = path;
    task.Show();
}

I would really appreciate any help.


回答1:


if imagePath is a Property of a class, try this

var item = listBox.SelectedItem as className; // like ShareMediaTask

var task = new ShareMediaTask();
task.FilePath = item.imagePath;
task.Show();



回答2:


If it's sent from the textblock, it would be your sender ... so you can do something like

var text = ((TextBlock)sender).Text;

Otherwise, you'll have to reference the property that it's binding to ...
Why, oh why will you name your textblock path ?? it'll confuse the hell out of everybody ... call it TextBlockPath, this way it's not ambiguous with just a path ...



来源:https://stackoverflow.com/questions/19968648/how-to-get-text-from-textblock-during-selectionchangeevent-from-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!