WPF字符串到双转换器

本文关键字:转换器 字符串 WPF | 更新日期: 2023-09-27 18:18:52

有人能给我一些提示,我可能做错了什么?

在xaml

中有一个textblock
<TextBlock>
  <TextBlock.Text>
    <Binding Source="signal_graph" Path="GraphPenWidth" Mode="TwoWay" Converter="{StaticResource string_to_double_converter}" />
  </TextBlock.Text>
</TextBlock>

附加到signal_graph的GraphPenWidth属性(double类型)。转换器在应用的资源中被声明为一个资源,看起来像这样:

public class StringToDoubleValueConverter : IValueConverter
  {
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
      double num;
      string strvalue = value as string;
      if (double.TryParse(strvalue, out num))
      {
        return num;
      }
      return DependencyProperty.UnsetValue;
    }
    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
      return value.ToString();
    }
  }

我认为会发生的是,在启动时,由默认构造函数选择的属性值将被传播到文本块,然后未来的文本块更改将在文本块离开焦点时更新图形。然而,初始加载并不更新文本块的文本,对文本块的文本的更改对图形的笔宽度值没有影响。

请随意要求进一步澄清。

WPF字符串到双转换器

不需要转换器,在属性上使用. tostring()方法。

public string GraphPenWidthValue { get { return this.GraphPenWidth.ToString(); } }

无论如何这是一个标准字符串值转换器:

 [ValueConversion(typeof(object), typeof(string))]
    public class StringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null ? null : value.ToString();
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }