WPF 画布缩放/变换以适合
-
19-09-2019 - |
题
我重新发布这个问题,因为上次我没有得到太多答复,希望重新措辞可能有所帮助......
本质上,我想做的是创建一个数据绑定画布,它将自动缩放其内容以“填充”可用空间。有点像缩放以适应操作。不幸的是,我的 WPF 技能还不是很强,我正在努力弄清楚如何完成最后一部分。我遵循了一些数据绑定示例来绑定画布,但不确定它是否错误并阻碍了我。
目前我有两个基本问题,具体取决于我尝试解决解决方案的方式:
- 如果可以使用变换,我不知道如何通过XAML自动使画布重新尺寸。
- 我似乎无法在背后代码中引用画布,我猜是因为它的一部分是eTemScontrol的一部分?
举一个我想要实现的目标的例子,我已经得到了 A,我想尝试得到 B:
(删除了 img 的过期链接)
我当前使用的代码非常简单,只需使用给定的坐标创建 4 个点,以及另一个视图模型来将它们包装起来。
public class PointCollectionViewModel
{
private List<PointViewModel> viewModels;
public PointCollectionViewModel()
{
this.viewModels = new List<PointViewModel>();
this.viewModels.Add(new PointViewModel(new Point(1, 1)));
this.viewModels.Add(new PointViewModel(new Point(9, 9)));
this.viewModels.Add(new PointViewModel(new Point(1, 9)));
this.viewModels.Add(new PointViewModel(new Point(9, 1)));
}
public List<PointViewModel> Models
{
get { return this.viewModels; }
}
}
public class PointViewModel
{
private Point point;
public PointViewModel(Point point)
{
this.point = point;
}
public Double X { get { return point.X; } }
public Double Y { get { return point.Y; } }
}
然后,PointCollectionViewModel 用作我的 AutoResizingCanvas 的 DataContent,它具有以下 XAML 来实现绑定:
<UserControl x:Class="WpfCanvasTransform.AutoResizingCanvas"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCanvasTransform"
x:Name="parent">
<ItemsControl x:Name="itemsControl" ItemsSource="{Binding Path=Models}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas x:Name="canvas" Background="DarkSeaGreen" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Canvas.LayoutTransform>
<ScaleTransform ScaleY="-1" />
</Canvas.LayoutTransform>
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:PointViewModel}">
<Ellipse Width="3" Height="3" Fill="Red"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Path=Y}"/>
<Setter Property="Canvas.Left" Value="{Binding Path=X}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</UserControl>
解决方案
身为你的 Canvas
似乎没有固定的宽度和高度,我会将其包含到 Viewbox
:
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Viewbox Stretch="Uniform">
<Canvas x:Name="canvas" Background="DarkSeaGreen">
<Canvas.LayoutTransform>
<ScaleTransform ScaleY="-1" />
</Canvas.LayoutTransform>
</Canvas>
</Viewbox>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
或者,将您的整个 UserControl
变成一个 ViewBox
.
不隶属于 StackOverflow