WPF 字符串到双转换器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17178738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:01:53  来源:igfitidea点击:

WPF string to double converter

c#wpfivalueconverter

提问by James Joshua Street

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

有人能给我一些关于我可能做错了什么的提示吗?

so I have a textblock in xaml

所以我在 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:

它附加到 signal_graph 的 GraphPenWidth 属性(双精度类型)。转换器在应用程序资源中声明为资源,如下所示:

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.

随时要求进一步说明。

回答by Smartis

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

不需要为此使用转换器,请在属性中使用 .ToString() 方法。

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