【问题标题】:Simple WPF formatting question简单的 WPF 格式问题
【发布时间】:2011-01-23 04:43:08
【问题描述】:

如何在 StackPanel 的 TextBlock 控件中为绑定值添加前缀,而不使用单独的控件作为前缀?

例如,假设我有一个对话框,它使用 TreeView 来显示书籍列表,顶部节点是标题,一组下级节点用于其他书籍属性(ISBN、作者等)。

我的绑定工作正常,但我的用户希望书籍属性列表垂直堆叠,并且显然,他希望每个属性节点在值之前都有一个描述性前缀(例如,“作者: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 书籍,但我想我不知道搜索我想说的内容的正确方法。

谢谢!

【问题讨论】:

    标签: wpf xaml formatting


    【解决方案1】:

    如果您有 .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,但您可能希望在绑定失败或读取为 null 时提供备用值
    • 为此您可以提供 {Binding FallbackValue=Something}。如果绑定失败,这将起作用。或者你可以使用优先绑定
    • 这就是我想要的。谢谢!自我注意:必须对 StringFormat 参数的花括号进行转义。
    【解决方案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 文件的静态资源中。

    【讨论】:

    • 很好的建议。我怀疑我需要为比我目前正在做的更复杂的事情这样做。谢谢!
    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多