Change the coordinate system of a Canvas in WPF

后端 未结 8 1939
一整个雨季
一整个雨季 2021-02-01 06:59

I\'m writing a mapping app that uses a Canvas for positioning elements. For each element I have to programatically convert element\'s Lat/Long to the canvas\' coordinate, then

8条回答
  •  没有蜡笔的小新
    2021-02-01 07:23

    Here's an all-XAML solution. Well, mostly XAML, because you have to have the IValueConverter in code. So: Create a new WPF project and add a class to it. The class is MultiplyConverter:

    namespace YourProject
    {
        public class MultiplyConverter : System.Windows.Data.IValueConverter
        {
            public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return AsDouble(value)* AsDouble(parameter);
            }
            double AsDouble(object value)
            {
                var valueText = value as string;
                if (valueText != null)
                    return double.Parse(valueText);
                else
                    return (double)value;
            }
    
            public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new System.NotSupportedException();
            }
        }
    }
    

    Then use this XAML for your Window. Now you should see the results right in your XAML preview window.

    EDIT: You can fix the Background problem by putting your Canvas inside another Canvas. Kind of weird, but it works. In addition, I've added a ScaleTransform which flips the Y-axis so that positive Y is up and negative is down. Note carefully which Names go where:

    
        
            
                
                    
                        
                            
                        
                        
                            
                        
                    
                    
                
            
            
            
            
        
    
    

    As for your new requirements that you need varying ranges, a more complex ValueConverter would probably do the trick.

提交回复
热议问题