简单的WPF格式化问题

5
如何在StackPanel中为TextBlock控件的边界值添加前缀,而不使用单独的控件来添加前缀?
例如,假设我有一个对话框,它使用TreeView显示书籍列表,其中顶级节点是标题,其下属节点是其他书籍属性(ISBN、作者等)的集合。
我已经正确绑定了数据,但我的用户希望书籍属性列表垂直堆叠,并且每个属性节点都要在值之前添加描述性前缀(例如,“作者:Erich Gamma”而不仅仅是“Erich Gamma”)。在我的HDT和DT元素内部,我使用了StackPanel和TextBlock控件来显示值。
我必须为每个属性的前缀使用单独的TextBlock控件吗?
<!-- Works, but requires 2 controls to display the book author and the prefix stacks above the author -->
<TextBlock Text="Author: "/><TextBlock Text="{Binding Path=Author}" />  

或者有没有一种方法可以使用单个TextBlock控件来处理每个节点?
<!-- only one control, but doesn't work -->
<TextBlock Text="Author:  {Binding Path=Author}" />  

我知道这可能是一个常见的问题,我已经在谷歌上搜索并查阅了我拥有的三本WPF书籍,但我猜我不知道如何正确地搜索我想要表达的内容。

谢谢!

2个回答

7

如果您已安装 .Net 3.5 SP1,您可以通过使用 StringFormat 轻松实现此目标。

<TextBlock Text="{Binding Path=Title, StringFormat= Title: {0}}" />

您也可以这样做

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat="Author: {0}, Title: {1}">
      <Binding Path="Author"/>
      <Binding Path="Title"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

如果您没有使用SP1版本, 那么您可以使用一个值转换器。

你的方法比我的更简洁 :) - slugster
+1,但是当绑定失败或读取null时,您可能需要提供一个备用值。 - Rob Fonseca-Ensor
你可以使用 {Binding FallbackValue=Something} 来实现这个功能,当绑定失败时它会生效。或者你也可以使用优先级绑定。 - SysAdmin
那就是我一直在寻找的。谢谢!自己注意:StringFormat参数的花括号必须进行转义。 - Minnow Noir

3

快速简单的方法:使用转换器,并将前缀文本作为转换器参数传递。然后在转换器中,您只需将转换器参数文本添加到绑定文本之前即可。

<TextBlock Text="{Binding Path=Title, Converter={StaticResource MyTextConverter}, ConverterParameter=Title}" />
<TextBlock Text="{Binding Path=ISBNNumber, Converter={StaticResource MyTextConverter}, ConverterParameter=ISBN}" />
<TextBlock Text="{Binding Path=AuthorName, Converter={StaticResource MyTextConverter}, ConverterParameter=Author}" />

public class MyTextConverter : IValueConverter 
{

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is string)
        {
            return string.Format("{0}{1}{2}", parameter ?? "", !string.IsNullOrEmpty(parameter) ? " : " : "", value);
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

这是我脑海中想到的,可能有些小错误,请见谅。使用一个文本块即可完成此操作。您只需要在xaml文件的静态资源中包含转换器即可。


好建议。我怀疑如果我要做比我目前正在做的更复杂的事情,我就需要这样做。谢谢! - Minnow Noir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接