A simple WPF formatting question

How can I prefix related values ​​in TextBlock controls in a StackPanel without using separate controls for prefixes?

For example, let's say I have a dialog that uses TreeView to display a list of books, with the top nodes being the title and a set of subordinate nodes for other attributes of the book (ISBN, Author, etc.).

I have a binding that works correctly, but my user wants the list of book attributes to stack vertically, and obviously he wants each node attribute to have a descriptive prefix before the value (for example, "Author: Erich Gamma") and not just " Erich Gamma "). Inside my HDT and DT elements, I use the StackPanel and TextBlock elements to display the values.

Should I use a separate TextBlock control to prefix each attribute

<!-- 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}" />  

or is there a way to do this with a single TextBlock control for each node?

<!-- only one control, but doesn't work -->
<TextBlock Text="Author:  {Binding Path=Author}" />  

I know this should be a common problem, and I Googled for it and looked in my three WPF books, but I think I don’t know how to correctly search for what I'm trying to say.

Thank!

+5
source share
2 answers

If you have .Net 3.5 SP1, you can easily achieve this via StringFormat

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

You can also do it

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

If you are not using SP1, then you can use ValueConverter

+6
source

: . , , .

<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.

+2

All Articles