如何将多个值绑定到一个标签?

时间:2014-04-19 14:13:11

标签: c# wpf imultivalueconverter

我已经从Link实现了IMultiValueConverter,将多个值绑定到一个标签。

namespace MyApp
{
[ValueConversion(typeof(object), typeof(string))]
public class ConcatenateFieldsMultiValueConverter : IMultiValueConverter
{
  public object Convert(
           object[] values,
           Type targetType,
           object parameter,
           System.Globalization.CultureInfo culture
        )
{
  string strDelimiter;
  StringBuilder sb = new StringBuilder();

  if (parameter != null)
  {
     //Use the passed delimiter.
     strDelimiter = parameter.ToString();
  }
  else
  {
     //Use the default delimiter.
     strDelimiter = ", ";
  }

  //Concatenate all fields
  foreach (object value in values)
  {
     if (value != null && value.ToString().Trim().Length > 0)
     {
        if (sb.Length > 0) sb.Append(strDelimiter);
        sb.Append(value.ToString());
     }
  }

  return sb.ToString();
}

public object[] ConvertBack(
           object value,
           Type[] targetTypes,
           object parameter,
           System.Globalization.CultureInfo culture
     )
{
  throw new NotImplementedException("ConcatenateFieldsMultiValueConverter cannot convert back (bug)!");
}
}
}

然而,当我引用

xmlns:local="clr-namespace:MyApp"

在XAML(命名空间MyApp)中的Window Properties中,在Window

中定义以下内容
<Window.Resources>
  <local:ConcatenateFieldsMultiValueConverter x:Key="mvc"/>
</Window.Resources>

我的单独类ConcatenateFieldsMultiValueConverter无法识别。

你能想象为什么在Window.Resources中无法识别这个类吗?

2 个答案:

答案 0 :(得分:2)

如果您可以使用 TextBlock ,则只需使用XAML即可完成任何转换器。

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1}">
            <Binding Path="Property1"/>
            <Binding Path="Property2"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

但它不适用于Label,因为它使用Content属性而不是Text。因此无法应用StringFormat。


对于 Label ,您必须使用 IMultiValueConverter 。就像在评论中提到的那样尝试重新编译你的项目,因为发布的代码似乎很好。

答案 1 :(得分:0)

首先编译它,看起来你只是设计时错误。我尝试重现你的问题,当我重新编译它就消失了。

它也在运行时运行。