XAML中ItemsSource的自定义对象数组,用于设计预览
本文关键字:用于 数组 ItemsSource 自定义 对象 XAML | 更新日期: 2023-09-27 18:10:11
我想用ItemsControl
在Canvas
上绘制自定义类的对象。为了在VisualStudio 设计器中具有某种预览,我将添加一个ItemsSource
和一些演示对象的Collection
。但是我不知道如何声明我的对象的集合。
与Point
我可以使用PointCollection
:
<ItemsControl Name="pointsItems2">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Width="100" Height="100">
<Canvas.Background>
<SolidColorBrush Color="LightGray" Opacity="0.5"/>
</Canvas.Background>
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse Width="10" Height="10" Stroke="Red" StrokeThickness="1" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<!-- Setting the position with a style is necessary. Setting parent properties in the template does not work -->
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<!-- The offset converter moves the center of the circle to the desired position. ConverterParameter is the offset.-->
<Setter Property="Canvas.Left" Value="{Binding X, Converter={StaticResource ResourceKey=OffsetConverter}, ConverterParameter='-5'}"/>
<Setter Property="Canvas.Bottom" Value="{Binding Y, Converter={StaticResource ResourceKey=OffsetConverter}, ConverterParameter='-5'}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemsSource>
<PointCollection>
<Point X="0" Y="0" />
<Point X="10" Y="10" />
<Point X="20" Y="40" />
<Point X="30" Y="90" />
</PointCollection>
</ItemsControl.ItemsSource>
</ItemsControl>
现在我有了一个类,它具有用作坐标的属性,但也有稍后需要具有图形表示的其他属性。我想把字面指定的ItemsSource改为代表类对象的东西。我想到了
<x:Array Type="{x:Type Point}">
<Point X="0" Y="0"/>
<Point X="100" Y="100"/>
</x:Array>
这里的问题是,当我想实例化我的类时,将调用默认构造函数,我可以通过属性设置属性,但是我的类依赖于参数化构造函数和公共属性,没有有公共设置器。如何用一种优雅的、类似WPF/xhtml的方式来完成呢?
基本上不能。XAML 2009支持传递构造函数参数,但根据MSDN,这并不适用于WPF——至少不是以你描述的方式。它可以在后来包含的XAML文件中,但不能在编译文件中,所以我认为它不会在设计器中工作。
为什么不能创建一个无参数的构造函数并将属性更改为具有公共setter ?
如果有很好的理由不这样做,那么可以为参数创建一个虚拟保存类,并使用ValueConverter将ItemsSource绑定到这些虚拟类的集合,以从虚拟类转到您想要的类。这样,您可以在代码中构造并使用参数化的构造函数。