简单的WPF格式问题

时间:2010-03-03 12:41:56

标签: wpf xaml formatting

如何在不对前缀使用单独的控件的情况下为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}" />  

我知道这一定是一个常见的问题,我用Google搜索并搜索了我所拥有的三本WPF书籍,但我想我不知道正确的方法来搜索我想说的内容。< / p>

谢谢!

2 个答案:

答案 0 :(得分:6)

如果你有.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, 然后你可以使用ValueConverter

答案 1 :(得分:2)

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

<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文件的静态资源中。

相关问题