2013-07-28 26 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}"/> 
相關問題