简体   繁体   中英

Customize text of TextBlock Text within ListBox dynamically

I have a ListBox with a custom DataTemplate as follows:

<ListBox>
     <ListBox.ItemTemplate>
          <DataTemplate>
               <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Value}" />
               </StackPanel>
          </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

I would like to customize the TextBlock contents based on the value of another control on the page which is used to filter the items in the ListBox. So if the filter control had the text "Hello" in it, a list item with text of "Hello World!" would appear as Hello world! (with "Hello" bolded).

I am not sure where to hook in this type of custom formatting. I thought about using a Converter, but they only support a single parameter and multivalueconverters are a no-go still in Silverlight 4. I thought about an event where I could iterate through the items, but none seems to be present in the ListBox or at the Item level. I saw this option , but I have to wonder if there is not a simpler solution to this problem.

UPDATE: This is even make more complicated by the fact that I will need to use multiple RUN blocks since matches can occur in multiple locations within a string. Eg Hello world Hello would have two matches.

I think you can accomplish this with a converter. You would just pass in the value of the filter textbox in the ConverterParameter. Your binding would look something like this:

<TextBlock Text="{Binding Value, Converter={StaticResource YourConverterName}, ConverterParameter={ElementName=FilterTextBox, Path=Text}}" />

Convert method for reference:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

At that point, in your Convert method, you would have the text of the TextBlock via the value parameter, and the text of the filter TextBox via the "parameter" parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM