WPF string to double converter

三世轮回 提交于 2019-12-10 20:21:59

问题


Could someone give me some hints as to what I could be doing wrong?

so I have a textblock in xaml

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

which attached to signal_graph's GraphPenWidth property (of type double). The converter is declared as a resource in the app's resources and looks like this:

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();
    }
  }

What I thought would happen is that on startup the property value chosen by the default constructor would be propagated to the textblock, and then future textblock changes would update the graph when the textblock left focus. However, instead initial load does not update the textblock's text and changes to textblock's text have no effect on the graph's pen width value.

feel free to ask for further clarification.


回答1:


You do not need a converter for this, use the .ToString() method at the property.

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

Anyway here is a Standart String Value Converter:

 [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();
        }
    }


来源:https://stackoverflow.com/questions/17178738/wpf-string-to-double-converter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!