C# WPF ItemsControl数据模板未显示在画布上
我目前正在开发一个.NET4.7.1应用程序。我使用XAML WPF UI。我需要根据绑定视图模型中列表中的值在画布上显示矩形 我可以在画布上显示静态矩形,但是我不知道如何从ItemsControl数据模板显示矩形。 另外,我需要为我的矩形使用某种样式。我在Canvas.Resources中定义了样式 我当前的编码如下所示:C# WPF ItemsControl数据模板未显示在画布上,c#,wpf,xaml,canvas,itemscontrol,C#,Wpf,Xaml,Canvas,Itemscontrol,我目前正在开发一个.NET4.7.1应用程序。我使用XAML WPF UI。我需要根据绑定视图模型中列表中的值在画布上显示矩形 我可以在画布上显示静态矩形,但是我不知道如何从ItemsControl数据模板显示矩形。 另外,我需要为我的矩形使用某种样式。我在Canvas.Resources中定义了样式 我当前的编码如下所示: <Canvas x:Name="canvas" Grid.Row="2" ClipToBounds="True" Background="Gainsboro">
<Canvas x:Name="canvas" Grid.Row="2" ClipToBounds="True" Background="Gainsboro">
<Canvas.Resources>
<Style TargetType="Rectangle">
<Setter Property="Fill">
<Setter.Value>
<DrawingBrush TileMode="Tile"
Viewport="0,0,2,5" ViewportUnits="Absolute"
Viewbox="0,0,2,30" ViewboxUnits="Absolute">
<DrawingBrush.Transform>
<RotateTransform Angle="45"/>
</DrawingBrush.Transform>
<DrawingBrush.Drawing>
<GeometryDrawing>
<GeometryDrawing.Pen>
<Pen Brush="Red" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<LineGeometry StartPoint="0,15" EndPoint="30,15"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</Setter.Value>
</Setter>
</Style>
</Canvas.Resources>
<!-- The static Rectangle works fine -->
<!--<Rectangle Width="100" Height="100" Canvas.Left="100" Canvas.Top="100"/>-->
<ItemsControl ItemsSource="{Binding RItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="{Binding Width}" Height="{Binding Height}" Canvas.Left="{Binding Y}" Canvas.Right="{Binding X}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid Width="{Binding ActualWidth, ElementName=canvas}" Height="{Binding ActualHeight, ElementName=canvas}">
<Label Content="Beginning" FontWeight="Bold" VerticalAlignment="Center" HorizontalAlignment="Left">
<Label.LayoutTransform>
<RotateTransform Angle="270"/>
</Label.LayoutTransform>
</Label>
<Label Content="End" FontWeight="Bold" VerticalAlignment="Center" HorizontalAlignment="Right">
<Label.LayoutTransform>
<RotateTransform Angle="270"/>
</Label.LayoutTransform>
</Label>
</Grid>
</Canvas>
public List<RItem> RItems { get; set; } = new List<RItem>
{
new RItem
{
X = 100,
Y = 100,
Width = 100,
Height = 100
}
};
你知道我做错了什么吗?如何在画布上显示视图模型类中的RItem
非常感谢 画布应位于itemscontrol中,因为它是itemspanel 大致上类似于:
<ItemsControl ItemsSource="{Binding RItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
.....
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding Left}" />
<Setter Property="Canvas.Top" Value="{Binding Top}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
.....
还要注意的是,每个项目都放在一个容器中,必须将其放置在画布上
我不知道为什么网格会绑定到画布的大小。将itemcontrol放入网格中,它将填充网格