2

一般来说,我对编程完全陌生,但我已经自学 C# 大约 6 个月了。目前正在研究 WPF/XAML。我正在尝试学习如何在 WPF 中渲染形状。

我在自定义类中创建了一个路径,我的 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);
        }


    }
}
4

1 回答 1

1

您正在将您的DataDP绑定到不起作用Path的类型的对象。Path

DataGeometry类型,因此您需要绑定到将返回Geometry而不是返回的对象Path

制作你pathGeomerty的 aproperty并与之绑定 -

public PathGeometry Geometry
{
   get
   {
      return pathGeometry ;
   }
}

XAML -

<Path Data="{Binding Path=chartmaker.Geometry}"/>
于 2013-07-28T07:26:18.767 回答