WPF Units and Code-Behind

后端 未结 2 1794
不思量自难忘°
不思量自难忘° 2021-02-19 09:31

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 a

2条回答
  •  滥情空心
    2021-02-19 10:15

    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");
    

    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.

    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.

提交回复
热议问题