2012-08-10 56 views
0

我正在使用MVVM開發WPF/XAML應用程序,並將字符串集合作爲viewmodel上的一個屬性。我想連接字符串以在文本塊或類似控件中顯示。字符串應該使用文本「AND」連接,並且連接文本應該使用粗體字體重樣式。輸出會是這個樣子:如何在XAML中連接並設置字符串列表?

鼠標

什麼是實現我的最終結果的最佳方式?

回答

1

既然你不能綁定到只讀TextBlock.Inlines財產,我會建議創建一個派生的TextBlock有TextList屬性:

public class TextListBlock : TextBlock 
{ 
    public static readonly DependencyProperty TextListProperty = DependencyProperty.Register(
     "TextList", typeof(IEnumerable<string>), typeof(TextListBlock), 
     new PropertyMetadata((o, e) => ((TextListBlock)o).TextListChanged((IEnumerable<string>)e.NewValue))); 

    public IEnumerable<string> TextList 
    { 
     get { return (IEnumerable<string>)GetValue(TextListProperty); } 
     set { SetValue(TextListProperty, value); } 
    } 

    private void TextListChanged(IEnumerable<string> textList) 
    { 
     bool addSeparator = false; 
     foreach (string text in textList) 
     { 
      if (addSeparator) 
      { 
       Inlines.Add(new Run(" AND ") { FontWeight = FontWeights.Bold }); 
      } 

      Inlines.Add(new Run(text)); 
      addSeparator = true; 
     } 
    } 
} 
+0

不錯!這個解決方案比我提出的解決方案更簡單並且提供了更好的可重用性。 – Scott 2012-08-13 15:44:52

0

我結束了在集合中的每個項目創建一個視圖模型(以我爲例的動物)。在這樣做的時候,我添加了一個名爲IsNotLast的屬性,它可以幫助我確定何時應該在項目之間顯示「AND」文本。此外,我使用了BooleanToVisibilityConverter,這樣我的XAML中的可見性屬性就會被適當地設置。

下面是使用ItemsControl和DataTemplate的示例XAML。

<ItemsControl ItemsSource="{Binding Path=Animals}"> 
<ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <StackPanel Orientation="Horizontal"> 
      <TextBlock 
     Text="{Binding AnimalName}" 
    /> 
      <TextBlock 
     Text=" AND " 
     FontWeight="Bold" 
     Visibility="{Binding IsNotLast, Converter={StaticResource booleanToVisibilityConverter}}" 
    /> 
     </StackPanel> 
    </DataTemplate> 
</ItemsControl.ItemTemplate> 
<ItemsControl.ItemsPanel> 
    <ItemsPanelTemplate> 
     <StackPanel Orientation="Horizontal"/> 
    </ItemsPanelTemplate> 
</ItemsControl.ItemsPanel> 

相關問題