2017-02-26 103 views
0

雖然我稍微簡化了需求,但我需要顯示一些帶有下劃線的字符,有些不在列表框項目中 - 下劃線用於從數據庫中讀取的字符串中,以指示哪些字符需要在GUI上大膽。使列表框項目中的某些字符加下劃線

例如,如果一個字符串包含「The f_at ca_t sat」,那麼列表框中顯示的項目將只有a和t下劃線。

我真的不知道如何實現這一點 - 我想我需要定義一個ItemTemplate,但不知何故,但是當你不知道哪些文本將被預先加下劃線(或者即使有下劃線的文本),那麼您無法定義<運行>元素。

任何幫助非常感謝。

回答

1

不幸的是,您無法綁定TextBlock的Inlines屬性。

您可以但是創建一個PropertyChangedCallback直接訪問Inlines集合的附加屬性:

public static class TextBlockEx 
{ 
    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.RegisterAttached(
      "Text", 
      typeof(string), 
      typeof(TextBlockEx), 
      new PropertyMetadata(null, TextPropertyChanged)); 

    public static string GetText(DependencyObject obj) 
    { 
     return (string)obj.GetValue(TextProperty); 
    } 

    public static void SetText(DependencyObject obj, string value) 
    { 
     obj.SetValue(TextProperty, value); 
    } 

    private static void TextPropertyChanged(
     DependencyObject obj, DependencyPropertyChangedEventArgs e) 
    { 
     var textBlock = obj as TextBlock; 

     if (textBlock != null) 
     { 
      var text = (string)e.NewValue; 

      textBlock.Inlines.Clear(); 
      // textBlock.Inlines.Add(new Run(text)); 
      // add Runs and Underlines as necessary here 
     } 
    } 
} 

鑑於您的列表框綁定到字符串的集合,你可以使用屬性在XAML這樣的:

<ListBox ItemsSource="{Binding Strings}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock local:TextBlockEx.Text="{Binding}"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 
相關問題