如何用C#替换XAML路径的数据

时间:2014-11-03 11:56:08

标签: c# xaml drawing windows-8.1 win-universal-app

我有一个XAML路径......

<Path x:Name="test" Stretch="Uniform" Fill="#FF2A2A2A" Data="F1 M 9143.18... Z "/>

我想更改&#34;数据&#34;通过C#这样(我将新路径数据作为字符串)...

test.Data = "F1 M 987... Z";

如何为通用应用程序(8.1)实现此目标?

这应该有效,但它没有(Windows.UI.Xaml.Media.Geometry不包含&#39; Parse&#39;的定义)

test.Data = Geometry.Parse("F1 M 987... Z");

任何帮助或指导都将不胜感激。

提前谢谢。

好的,谢谢......这是我的工作方式......

<Path x:Name="test" Stretch="Uniform" Fill="#FF2A2A2A" Data="{Binding}"/>

test.DataContext = "F1 M 987... Z";

2 个答案:

答案 0 :(得分:2)

如果要将字符串解析为Geometry,可以使用XamlReader.Load。一旦你有了Geometry,你就可以像BCdotNet建议的那样绑定它(但是你可能想要发出更改通知)或者明​​确地设置数据

// Parse the path-format string into a Geometry
Geometry StringToPath(string pathData)
{
    string xamlPath = 
        "<Geometry xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" 
        + pathData + "</Geometry>";

    return Windows.UI.Xaml.Markup.XamlReader.Load(xamlPath) as Geometry;
}

// In some function somewhere...
// Set the path either directly
test.Data = StringToPath("M 282.85714,355.21933 160,260.93361 260,169.50504 448.57143,163.79075 494.28571,286.6479 z");
// Or via data binding
PathGeometry = StringToPath("M 282.85714,355.21933 160,260.93361 260,169.50504 448.57143,163.79075 494.28571,286.6479 z");
//....

// If we want changes to the bound property to take effect we need to fire change notifications
// Otherwise only the initial state will apply
Geometry _geometry;
public Geometry PathGeometry
{
    get
    {
        return _geometry;
    }
    set
    {
        _geometry = value;
        NotifyPropertyChanged("PathGeometry");
    }
}

答案 1 :(得分:1)

您需要Bind it

C#:

public PathGeometry Geometry
{
   get
   {
      return pathGeometry ;
   }
}

XAML:

<Path Data="{Binding Path=chartmaker.Geometry}"/>