WPF中的类型转换器

问题描述 投票:2回答:3

我阅读了这篇文章,但对于类型转换器及其用法仍然不太清楚。

http://msdn.microsoft.com/en-us/library/aa970913.aspx

谁能解释一下它是什么以及在WPF中可以用它做什么。

wpf wpf-controls
3个回答
2
投票

例如,当您在XAML中设置背景属性时,您可以编写“ Red”,在后面的代码中,您不能仅给Background属性提供字符串“ Red”,因为其类型是Brush。WPF使用类型转换器将字符串转换为画笔。


7
投票

如果您具有的属性不是string类型,但是需要通过XAML属性进行设置,则需要将XAML中指定的string转换为目标属性类型。因此,请使用类型转换器。


0
投票

此示例来自WPF 4.5 Unleashed,该书对XAML声明性语言进行了广泛介绍。某些页面可以在Google Books上读取。

如果要指定Button对象的背景色,只要不将类型转换器明确地添加到我们使用的类中,这就是我们需要做的:

<Button>
    <Button.Background>
        <SolidColorBrush>
            <SolidColorBrush.Color>
                <Color A = "255" R="255" G="255" B="255" />
            </SolidColorBrush.Color>
        </Button.Background>
    </SolidColorBrush>
</Button>

在此声明中,

<Button.Background>
    <SolidColorBrush>

意味着我们要创建SolidColorBrush的实例并将其分配给Button.Background属性(实际上是Control.Background),其类型是抽象类型Control.Background

类似地,

Brush

意味着我们要创建具有相应属性的Brush的实例,并将该实例分配给类型为<SolidColorBrush.Color> <Color A = "255" R="255" G="255" B="255" /> Color

通过使用显式转换器,可以理解将字符串文字SolidColorBrush.Color作为SolidColorBrush.Color XML元素的内容提供时,必须将其转换为Color实例,这是第一个简化。现在,这种简化使我们可以编写:

Color

通过指定White,已明确将使用这种转换器的可能性添加到SolidColorBrush.Color类的声明中。该转换器说:“ 当遇到文字<Color A = "255" R="255" G="255" B="255" />(或<Button> <Button.Background> <SolidColorBrush> <SolidColorBrush.Color> White </SolidColorBrush.Color> </Button.Background> </SolidColorBrush> </Button> )作为Color元素的内容时,请实例化具有某些特定属性的type converter attribute,并将其分配给White元素

我们还可以在white类声明中添加类似的类型转换器属性,以直接理解Color

Color

此处Color上的转换器将不实例化SolidColorBrush对象,而是直接实例化White,其<Button> <Button.Background> <SolidColorBrush> White </Button.Background> </SolidColorBrush> </Button> 属性为白色SolidColorBrush

让我们进一步前进,并在类型为ColorSolidColorBrush上添加类型转换器,因此接受大于Color的对象。此转换器将替换Color实例中的有效字符串文字内容,现在允许:

Control.Background

这是解释XML内容时XAML所允许的简化背后的机制。如果使用后面的代码,则无法进行这种简化,并且代码必须等效于XAML中按钮声明的长初始版本。

XAML允许的最后一种简化:我们可以使用XAML的属性语法而不是元素语法:

Brush

哇!我们将所需行数除以10!

© www.soinside.com 2019 - 2024. All rights reserved.