WinForms中的TypeConverters可以在WPF中使用吗?

问题描述

C#,WPF。在WPF应用程序中,我最初从WinForms获得了类,这些类具有TypeConverters和相应的装饰器。从网上可以找到的信息来看,TypeConverter似乎不受普遍支持,并且往往主要在Winforms中使用。但是我无法对其WPF的范围/适用性找到清晰,简单的解释。

我创建了以下最小示例。 LatitudeLongitudedoubles,我希望它们以xceed PropertyGrid的形式出现,并以strings格式(现有)为TypeConverter。在最简单的情况下,这种格式将添加度数符号,但是在不同的度量单位之间也会进行转换。

此处显然未使用TypeConverter。我在PropertyGrid中看到“ 1”和“ 2”,在TextBox中看到“ 1”。

它应该以这种方式工作,还是我需要以更WPF为中心的方式重写(例如ValueConverter:IValueConverter)?

<Window x:Class="PropertyGridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PropertyGridTest"
        xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel Orientation="Vertical">
            <xctk:PropertyGrid Name="propertyGrid"/>
            <TextBox Name="textBox" Text="{Binding Path=Latitude}"/>
        </StackPanel>
    </Grid>
</Window>

namespace PropertyGridTest
{

    public class Foo {
        [TypeConverter(typeof(degreesTypeConverter))]
        public double Latitude { get; set; } = 1.0;
        [TypeConverter(typeof(degreesTypeConverter))]
        public double Longitude { get; set; } = 2.0;
    }

    public partial class MainWindow : Window
    {
        Foo bar = new Foo();
        public  MainWindow()
        {
            InitializeComponent();
            propertyGrid.AutoGenerateProperties = true;
            propertyGrid.Selectedobject = bar;
            textBox.DataContext = bar;
        }
    }

    public class degreesTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context,Type sourceType)
        {
            return sourceType == typeof(string);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context,Type destinationType)
        {
            return destinationType == typeof(string);
        }
        public override object ConvertFrom(ITypeDescriptorContext context,CultureInfo culture,object value)
        {
            return (value is string) ? 999.0 : 0.0;
        }

        public override object ConvertTo(ITypeDescriptorContext context,object value,Type destinationType)
        {
            return (destinationType == typeof(string)) ? "[formatted string]" : "";
        }
    }

}

解决方法

它应该以这种方式工作,还是我需要以更WPF为中心的方式进行重写(例如ValueConverter:IValueConverter)?

是的,WPF使用值转换器将源属性的值从一种类型转换为另一种类型。如果未指定,则它将使用一个内置的转换器,该转换器基本上只对值调用ToString()。框架不会检查数据绑定属性是否用[TypeConverter]属性修饰。

但是,

TypeConverters用于将XAML字符串转换为其他类型。有关更多信息,请参考docs