Home > Blockchain >  How to Get SelectedItem as DataTemplate in Listview?
How to Get SelectedItem as DataTemplate in Listview?

Time:06-24

I have a listview Which is defined as follows:

<DataTemplate x:Name="myTemplate" x:DataType="table:myItem">
  <RichTextBlock Margin="10" IsTextSelectionEnabled="False">
    <Paragraph x:Name="txtParagraph">
      ....
    </Paragraph>
  </RichTextBlock>
</DataTemplate>

<ListView name="lst" ItemTemplate="{StaticResource myTemplate}"/>

lst.ItemSource = someData;

Now I want to get paragraph from the DataTemplate of the current item something like this:

paragraph = GetParagraphFromItem(listview.selectedItem)

How can I do this?

CodePudding user response:

How to Get SelectedItem as DataTemplate in Listview?

You could get each ListViewItem with ContainerFromItem method and then you could access item's ContentTemplateRoot property to get RichTextBlock. And Paragraph was stored in RichTextBlock's Blocks collection.

 var listviewItem = MyListView.ContainerFromItem(yourselecteditem) as ListViewItem;
 RichTextBlock rtb = listviewItem.ContentTemplateRoot as RichTextBlock;
 var txtParagraph = rtb.Blocks.Where(p => p.Name == "txtParagraph").FirstOrDefault();
  • Related