2

The default unit for the size of every user control is px, but it is possible to easily set the size to a different unit, for instance:

<Canvas Height="29.7cm" Width="21cm" />

But what should I do if I want to bind these properties? How do I retain the information about my desired unit?

SG_90
  • 195
  • 3
  • 14
  • 2
    Maybe have a look at the approach described [in this answer](http://stackoverflow.com/a/9508847/1834662) – Viv Aug 27 '14 at 13:50

1 Answers1

0

You can create a custom converter which converts the string representation to double (using LengthConverter):

[ValueConversion(typeof(string), typeof(double))]
public class SizeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double size = (double)new LengthConverter().ConvertFrom(value.ToString());
        return size;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("SizeConverter is a oneway converter.")
    }
}

After that you can refer that converter from your XAML:

<src:SizeConverter x:Key="sizeConverter"/>

<Canvas Height="{Binding Path=Height, Converter={StaticResource sizeConverter}}" 
        Width="{Binding Path=Width, Converter={StaticResource sizeConverter}}" />

(Here Height and Width are strings available in the DataContext of your Canvas.)

qqbenq
  • 10,220
  • 4
  • 40
  • 45