2013-07-28 24 views
2

我完全不熟悉编程,但我一直在教自己C#约6个月。目前正在使用WPF/XAML。我试图了解WPF中的呈现形状。在XAML(带绑定)与C#中绘制路径。一个人可以工作,一个人不会

我有一个自定义类中创建的路径,我的AllocationCanvas在下面的XAML中绑定到该路径。无论出于何种原因,即使我知道绑定设置正确,它也不会画出来。

<Canvas x:Name="AllocationCanvas" 
        Grid.Row="0" 
        Grid.Column="0" 
        Width="Auto" 
        Height="Auto" 
        DataContext="{Binding RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type Window}}}"> 
    <Path Data="{Binding Path=chartmaker.myPath}"/> 

</Canvas> 

但是,如果我调用AllocationCanvas.Children.Add(myPath)它可以正常工作。我错过了什么?

public class ChartMaker { 

    private Dictionary<string, double> chartData; 
    Portfolio P; 
    public PathFigure arcs { get; set; } 
    private PathGeometry pathGeometry = new PathGeometry(); 
    public Path myPath { get; set; } 

    public ChartMaker(Portfolio portfolio) { 
     P = portfolio; 
     chartData = new Dictionary<string, double>(); 

     myPath = new Path(); 
     myPath.Stroke = Brushes.Black; 
     myPath.Fill = Brushes.MediumSlateBlue; 
     myPath.StrokeThickness = 4; 

     arcs = new PathFigure(); 
     arcs.StartPoint = new Point(100, 100); 
     arcs.IsClosed = true; 
     arcs.Segments.Add(new ArcSegment(new Point(200, 200), new Size(50, 50), 0, false, SweepDirection.Clockwise, true)); 
     arcs.Segments.Add(new ArcSegment(new Point(150, 350), new Size(10, 10), 0, false, SweepDirection.Clockwise, true)); 

     pathGeometry.Figures.Add(arcs); 

     myPath.Data = pathGeometry; 

     ProcessChartData(); 
    } 

    private void ProcessChartData() { 
     double TotalMarketValue = P.Positions.Sum(position => position.MarketValue); 

     foreach (Position position in P.Positions) { 
      double weight = position.MarketValue/TotalMarketValue; 
      chartData.Add(position.Ticker, weight); 
     } 


    } 
} 

回答

1

您结合您的PathData DP Path类型,这将无法正常工作的反对。

DataGeometry类型,所以你需要绑定到一个对象,它将返回Geometry而不是Path

让你pathGeomerty一个property,并把它绑定 -

public PathGeometry Geometry 
{ 
    get 
    { 
     return pathGeometry ; 
    } 
} 

XAML -

<Path Data="{Binding Path=chartmaker.Geometry}"/> 
相关问题