简单的WPF格式问题

Min*_*oir 5 wpf formatting xaml

如何在不使用单独的前缀控件的情况下为StackPanel中的TextBlock控件中的绑定值加前缀?

例如,假设我有一个对话框,它使用TreeView显示书籍列表,顶部节点是标题,另一个书籍属性(ISBN,作者等)的一组从属节点.

我的绑定工作正常,但我的用户希望书籍属性列表垂直堆叠,显然,他希望每个属性节点在值之前都有一个描述性前缀(例如,"作者:Erich Gamma"而不仅仅是"Erich"伽玛").在我的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}" />  
Run Code Online (Sandbox Code Playgroud)

或者有没有办法使用单个TextBlock控件为每个节点执行此操作?

<!-- only one control, but doesn't work -->
<TextBlock Text="Author:  {Binding Path=Author}" />  
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Sys*_*min 7

如果你有.Net 3.5 SP1,你可以通过StringFormat轻松实现

<TextBlock Text="{Binding Path=Title, StringFormat= Title: {0}}" />
Run Code Online (Sandbox Code Playgroud)

你也可以这样做

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat="Author: {0}, Title: {1}">
      <Binding Path="Author"/>
      <Binding Path="Title"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

如果您没有使用SP1,那么您可以使用ValueConverter