在 WPF 中为自定义框架元素实现 Stretch=“Fill”
本文关键字:Stretch Fill 实现 元素 WPF 自定义 框架 | 更新日期: 2023-09-27 17:56:23
我有一个自定义框架元素,它是对折线的对偶。此元素旨在在折线中点的位置绘制标记,并将充当叠加层。
我已经成功地绘制了点,但不知道如何实现折线等法线形状所具有的 Stretch="Fill" 功能。我的课程代码如下。
如果有人能启发我如何为此添加拉伸功能,我将不胜感激。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ReactiveUI;
namespace Weingartner.WPF
{
public class PolyMarkers : FrameworkElement
{
static PolyMarkers()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PolyMarkers), new FrameworkPropertyMetadata(typeof(PolyMarkers)));
}
public PointCollection Points
{
get { return (PointCollection)GetValue(PointsProperty); }
set { SetValue(PointsProperty, value); }
}
// Using a DependencyProperty as the backing store for Points. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PointsProperty =
DependencyProperty.Register(
"Points",
typeof(PointCollection),
typeof(PolyMarkers),
new PropertyMetadata(new PointCollection()));
private VisualCollection Children;
public PolyMarkers()
{
this.WhenAny(t => t.Points, x =>
{
return x.Value.Select(p =>
{
return CreateDrawingVisualEllipses(p, 10, 10);
});
}).Subscribe(x =>
{
foreach (var shape in x)
{
AddVisualChild(shape);
}
InvalidateMeasure();
InvalidateArrange();
InvalidateVisual();
});
}
private DrawingVisual CreateDrawingVisualEllipses(Point location, int dx, int dy)
{
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawEllipse(Brushes.Maroon, null, location, dx, dy);
drawingContext.Close();
return drawingVisual;
}
// Provide a required override for the VisualChildrenCount property.
protected override int VisualChildrenCount
{
get { return Children.Count; }
}
// Provide a required override for the GetVisualChild method.
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= Children.Count)
{
throw new ArgumentOutOfRangeException();
}
return Children[index];
}
}
}
最简单的方法是将Viewbox
包裹在整个元素的内容周围,并让它为您处理缩放。如果要在控件内的较低级别执行此操作,则需要重写所有度量和排列方法并手动执行所有缩放,这可能是很多(非常容易出错)的工作。