WPF 单元和代码隐藏 [英] WPF Units and Code-Behind

查看:17
本文介绍了WPF 单元和代码隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现 WPF 在 XAML 中支持不同的度量单位.除了默认的 DIP,还支持像素、英寸和厘米(据我所知).这允许设计者编写这样的 XAML:

Recently I discovered WPF supports different measurement units in XAML. Besides default DIPs, there is also support for pixels, inches and centimeters (as far as I know). This allows designer to write XAML such as this:

<Canvas>
    <Line X1="0cm" X2="3cm" Y1="1cm" Y2="3cm" Stroke="Black"/>
</Canvas>

但是,您不能绑定这些值.想象一下,我们有一个带有 Dimension 属性的 ViewModel,它是一个字符串,例如7cm".以下操作无效:

However, you cannot bind these values. Imagine we have a ViewModel with Dimension property which is a String, for example "7cm". Following won't work:

<Button Width="{Binding Dimension}">Test</Button>

FormatException 被抛出.同样,在代码隐藏中创建 FrameworkElement 时,如下所示:

FormatException gets thrown. Similarly, when creating a FrameworkElement in code-behind, like this:

Canvas1.Children.Add(new Button() { Width = "3cm", Content = "Test"});

编译失败,因为在构造函数中/在您尝试创建控件的任何地方抛出异常.

Compilation fails because exception is thrown in constructor/wherever you try to create the control.

我想知道:

  • 是否可以在代码隐藏中使用自然单位(在我的例子中是公制 - 厘米)?
  • 如何?
  • 是否有 WPF/XAML 支持的完整单元列表?

这是下面评论的链接,它解决了这个问题:

Here is a link from comment below, which resolves this question:

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.width.aspx

推荐答案

您可以通过应用 XAML 解析器使用的相同转换在代码中执行此操作,如果您不介意传递,则无需重新实现此逻辑围绕字符串:

You can do this in code behind by applying the same conversion the XAML-parser uses, you do not need to reimplement this logic if you don't mind passing around strings:

button.Width = (double)new LengthConverter().ConvertFrom("2cm");

XAML 解析器使用 TypeConverters 将字符串转换为所需的值,在 Width<的 文档页面中/code> 属性 你可以看到它有一个 TypeConverterAttribute 指定 应该使用 LengthConverter.此属性可用于在本地覆盖应如何处理属性,但它也可以应用于类级别,因此如果 Employee 类具有此属性,则指定 EmployeeConverter 应该使用表示转换器将是 Employee 类型属性的默认值.

The XAML-parser uses TypeConverters to convert strings to the needed values, in the documentation page of the Width property you can see that it has a TypeConverterAttribute specifying that a LengthConverter should be used. This attribute can be used to locally override how a property should be handled, but it can also be applied at class level, so if an Employee class has this attribute specifying that an EmployeeConverter should be used said converter will be the default for properties of type Employee.

我有点惊讶绑定没有应用这个类型转换器,但是在 IValueConverter 中使用它会很简单,事实上你可以创建一个 标记扩展,它从类型转换器构造一个 IValueConverter 以使其非常通用.

I am a bit surprised the binding does not apply this type converter, but using it inside an IValueConverter would be simple enough, in fact you could create a markup extension which constructs an IValueConverter from a type converter to make it nicely generic.

这篇关于WPF 单元和代码隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆