0
votes

I have a part of text which some of the words are formatted. These text are listed in a ListBox. When user clicks ListBoxitem, I want to collect that selectedItem and take user to the other place. My problem is that I cant bind TextBlock with another instance of TextBlock. And that TextBlock has many inlines, which I want to show.

I have been trying this solution:

<ListBox Width="800" Name="foundedTextBlocksListBox" SelectionChanged="foundedTextBlocksListBox_SelectionChanged" Background="Transparent" ItemsSource="{Binding}" Grid.Row="2" Visibility="Visible" Height="Auto" HorizontalAlignment="Center">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel VerticalAlignment="Center" Orientation="Vertical">
                    <TextBlock x:Name="foundedTextBlocks" DataContext="{Binding Textblock}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

After Binding to DataContext like this:

            ObservableCollection<FoundedTextBlock> listOfFoundedTextBlockResults = new ObservableCollection<FoundedTextBlock>();
            TextBlock textblock = new TextBlock();
            while (blockString.IndexOf("<b>") != -1)
            {
                int startOfWord = blockString.IndexOf("<b>");
                int endOfWord = blockString.IndexOf("</b>");
                string text = blockString.Substring(0, startOfWord);
                textblock.Inlines.Add(text);
                string boldedWord = blockString.Substring(startOfWord + 3, endOfWord - startOfWord - 3);
                textblock.Inlines.Add(new Run() { Text = boldedWord, FontWeight = FontWeights.Bold });
                blockString = blockString.Substring(endOfWord + 4);
                textblock.Inlines.Add(blockString);
            }
            textblock.Tag = dbInfo;
            listOfFoundedTextBlockResults.Add(new FoundedTextBlock() { Textblock = textblock });
        }
        foundedTextBlocksListBox.DataContext = listOfFoundedTextBlockResults;

I can't see any ListBoxItems in ListBox. Is my Binding wrong or is this possible at all? I managed before to get TextBlock.Text property to show but not the Inlines where are bolded text or any other Inlines after my first inline addition to TextBlock. How I can solve this annoiyng problem? In short, I need to display many TextBlocks with formatted text...

FoundedTextBlock class has TextBlock textblock {get;set;} property I'm saving to Tag property my class instance, so I could collect the information I need when SelectedValueChanged event occurs.

1

1 Answers

0
votes

Maybe you should use a ContentPresenter instead of TextBlock in your XAML

Replace

 <TextBlock x:Name="foundedTextBlocks" DataContext="{Binding Textblock}"></TextBlock>

with

<ContentPresenter Content="{Binding Textblock}" />

Please try it out ... the rest of your code is missing to provide a better answer.