应用于路径几何的数据绑定



我正在尝试通过将代码隐藏中定义的 PathFigureCollection 绑定到相应 UI 元素的 Figures 属性来呈现一个简单的图像。属性更改在调试器中显示为空,并且我尝试呈现的图形未显示。

这是我第一次实现数据绑定,所以我猜问题在于我对它的理解。我发现的大多数类似问题都是通过在 XAML 中设置 DataContext 变量或设置 Source 而不是 Path 来解决的。我实施了这些解决方案,但它们不能解决我的问题。

<Window x:Class="DrawingSandBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DrawingSandBox"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="754">
<Grid Margin="0,0,0,0">
<Image HorizontalAlignment="Left" Height="400" Margin="10,10,10,10" VerticalAlignment="Bottom" Width="700" RenderTransformOrigin="0.5,0.5">
<mage.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Pen>
<Pen Thickness="11" Brush="Black"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<PathGeometry Figures="{Binding Path=Frame, UpdateSourceTrigger=PropertyChanged}" /> 
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image> 
</Grid>

namespace DrawingSandBox 
{
public partial class MainWindow : Window
{
private static readonly CurveBuilder curve = new CurveBuilder();
public MainWindow()
{
InitializeComponent();
DataContext = curve;
}
}
public class CurveBuilder : INotifyPropertyChanged
{
private PointCollection points;
private PolyBezierSegment seg;
private PathFigureCollection frame;
public event PropertyChangedEventHandler PropertyChanged;
public PathFigure Figure;
public PathFigureCollection Frame
{
get
{
return frame;
}
set
{
if (value != frame)
{
frame = value;
NotifyPropertyChanged("Frame");
}
}
}
public CurveBuilder()
{
points = new PointCollection { new Point(20, 20), new Point(40, 40) };
seg = new PolyBezierSegment(points, true);
Figure = new PathFigure(new Point(50, 50), new PathSegmentCollection { seg }, false);
Frame = new PathFigureCollection { Figure };
}
public void NotifyPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}

就目前而言,此代码仅显示一个空白页。

您至少需要 3 分才能显示PolyBezierSegment

根据文档:

三次方贝塞尔曲线由四个点定义:起点、终点和两个 控制点。PolyBezierSegment 指定一条或多条三次方贝塞尔曲线,下式指定 将 Points 属性设置为点的集合。对于每三分 集合,第一点和第二点指定曲线的两个控制点 第三点指定终点。

绑定正确。再向PointCollection添加一个Point或使用PolyQuadraticBezierSegmentQuadraticBezierSegment

最新更新