1

我正在使用 MVVM 开发 WPF/XAML 应用程序,并将字符串集合作为我的视图模型上的属性。我想连接字符串以在文本块或类似控件中显示。字符串应使用文本“AND”连接,并且连接文本应使用粗体字重设置样式。输出看起来像这样:

猫和狗老鼠兔子_ _

实现我的最终结果的最佳方法是什么?

4

2 回答 2

2

由于您无法绑定到只读TextBlock.Inlines属性,因此我建议创建具有TextList属性的派生 TextBlock:

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;
        }
    }
}
于 2012-08-10T20:41:37.343 回答
0

我最终为集合中的每个项目(在我的示例中为动物)创建了一个 ViewModel。为此,我添加了一个名为 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>

于 2012-08-13T14:31:44.163 回答