Search code examples
c#windows-runtimewindows-store-appsmicrosoft-metrowinrt-xaml

Setting Path.Data in code-behind


I have this XAML code which makes a Path which is inside a Canvas residing in a MainPage.xaml page.

<Path x:Name="progressPath" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Stroke="Gold" StrokeThickness="5"
        Canvas.Left="300" Canvas.Top="300" Height="305" Width="305"
        Data="m 150,0 A 150,0 0 0 0 150,0 A 150,150 0 0 0 150,0">
    </Path>

I want to have several Path's like this one (for example, a new Path is made when the user taps a button), so I decided to create them in the code-behind - which doesn't seem to be possible.

The Path's Data is populated with the move and draw commands syntax which cannot directly be used as a text value (as shown above) in code-behind like it can be in xaml - I've found workarounds for this in Silverlight and I tried the same technique in my Metro/Windows-Store app but though it compiles correctly there is no Path on the screen.


tl;dr How do I create this Path in code-behind with the Data being as shown ?


Solution

  • I had this probelm too a while ago in winrt. It seems that you cannot asign a "path" value directly in code behind.

    However there is a solution here

    I used this class in winrt without any problem. All I had to do is change the signatures of the Convert and ConvertBack methods to implement the IValueConverter interface as it is in winrt and not in silverlight. Here they are

    public object Convert(object value, Type targetType, object parameter, string language)
        {
            string path = value as string;
            if (null != path)
                return Convert(path);
            else
                return null;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            PathGeometry geometry = value as PathGeometry;
    
            if (null != geometry)
                return ConvertBack(geometry);
            else
                return default(string);
        }
    

    Usage: (More or less)

    var stringToPathGeometryConverter = new StringToPathGeometryConverter();
    string pathData = "m 150,0 A 150,0 0 0 0 150,0 A 150,150 0 0 0 150,0" ;
    progressPath.Data = stringToPathGeometryConverter.Convert(pathData);