I have implemented the IMultiValueConverter from Link to bind multiple values to one label.

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)!");
}
}
}

However when I am referencing

xmlns:local="clr-namespace:MyApp"

in my Window Properties in XAML (namespace MyApp) and define the following within in Window

<Window.Resources>
  <local:ConcatenateFieldsMultiValueConverter x:Key="mvc"/>
</Window.Resources>

my seperate class ConcatenateFieldsMultiValueConverter is not recognized.

Could you imagine why this class cannot be identified in the Window.Resources?

有帮助吗?

解决方案

If you can use TextBlock, it can be done without any converter in place with only XAML.

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

But it won't work for Label because, it uses Content property and not Text. Hence StringFormat can't be applied.


For Label you have to use IMultiValueConverter. Like mentioned in comments try re-compiling your project because posted code seems fine.

其他提示

Compile it first, it looks like you are just getting design time error. I tried reproducing your problem and when I recompiled it went away.

It also runs in run time.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top