转换器,发送一个String并返回一个int

时间:2014-10-08 18:43:13

标签: c# wpf wpf-controls mahapps.metro

我在下面有这个转换器应该根据里面的字符数返回TextBox的宽度:

[ValueConversion(typeof(String), typeof(int))]
public class TextToWidth:IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    String g = (String)value;
    return  g.Length*10;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return null;
  }
}

在网格的ColumnDefinition中,我尝试使用此转换器,但收到了错误 IValueConverter的TypeConverter不支持从字符串转换。我知道Controls:TextboxHelper.Label是一个字符串:

<ColumnDefinition Width="{TemplateBinding Controls:TextboxHelper.Label, Converter=ToWidth}"/>

为什么会发生这种情况,是否有解决方案?

1 个答案:

答案 0 :(得分:1)

我只是改变了这一行:

<ColumnDefinition Width="{TemplateBinding Controls:TextboxHelper.Label, Converter=ToWidth}"/>

要:

<ColumnDefinition Width="{TemplateBinding Controls:TextboxHelper.Label, Converter={StaticResource ToWidth}}"/>