gpt4 book ai didi

c# - WPF Canvas 缩放/变换以适合

转载 作者:可可西里 更新时间:2023-11-01 03:00:53 31 4
gpt4 key购买 nike

我重新发布了这个问题,因为我上次没有得到太多回应,希望稍微重新措辞可能会有所帮助......

本质上,我想做的是创建一个数据绑定(bind) Canvas ,它将自动缩放其内容以“填充”可用空间。有点像缩放以适应操作。不幸的是,我的 WPF 技能还不是很强,我正在努力弄清楚如何完成这最后一部分。我遵循了一些数据绑定(bind)示例来绑定(bind) Canvas ,但不确定它是否错误并阻碍了我。

我目前有两个基本问题,具体取决于我尝试解决解决方案的方式:

  • 我不知道怎么做 Canvas 自动重新缩放如果可能的话,通过 XAML 使用转变。
  • 我好像不能在后面引用 Canvas 代码,我猜是因为它的一部分ItemsControl 的?

我正在努力实现的一个例子,我有 A 我想尝试并获得 B:

(删除了指向 img 的过期链接)

我目前使用的代码非常简单,只需创建具有给定坐标的 4 个点,以及另一个 View 模型来将它们包裹起来。

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 来实现绑定(bind):

<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

关于c# - WPF Canvas 缩放/变换以适合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236865/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com