Setting Path.Data in code-behind

故事扮演 提交于 2019-12-24 05:33:14

问题


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 ?


回答1:


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



回答2:


Another way to do it is to use XamlReader for this with apropriate string loaded. In C#6.0 it can look like this:

Path pathFromCode = XamlReader.Load($"<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'><Path.Data>{stringPathData}</Path.Data></Path>") as Path;


来源:https://stackoverflow.com/questions/31019687/setting-path-data-in-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!