这个问题在这里已经有了答案:
Add n rectangles to canvas with MVVM in WPF
(2 个回答)
4年前关闭。
如何使用 MVVM 将矩形添加到我的 View 中?
这是我的观点的代码。
<Grid>
<Image x:Name="img" Source="{Binding ImagePath, Source={x:Static vm:DrawingVM.instance}, Converter={StaticResource nullImageConverter}}" Stretch="None" >
</Image>
<ItemsControl ItemsSource="{Binding ListRectangle, Source={x:Static vm:DrawingVM.instance}}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Transparent" x:Name="cnvas" Width="{Binding ElementName=img, Path=ActualWidth}"
Height="{Binding ElementName=img,Path=ActualHeight}"
LayoutTransform="{Binding ElementName=img, Path=LayoutTransform}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<!--<command:EventToCommand CommandParameter="{Binding ElementName=cnvas}" Command="{Binding MouseDownCommand, Source={x:Static vm:DrawingVM.instance}}" PassEventArgsToCommand="True" />-->
<ei:CallMethodAction MethodName="MouseDownEvente" TargetObject="{Binding Source={x:Static vm:DrawingVM.instance}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding X}"/>
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="{Binding Width}" Height="{Binding Height}" Stroke="Blue" Fill="Transparent" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
这是我的 View 模型
Canvas canvas = new Canvas();
public void MouseDownEvente(object s, MouseButtonEventArgs e)
{
try
{
if (s == null) return;
canvas = s as Canvas;
if (canvas == null) return;
startPoint = e.GetPosition(canvas);
// Remove the drawn rectanglke if any.
// At a time only one rectangle should be there
//if (rectSelectArea != null)
// canvas.Children.Remove(rectSelectArea);
// Initialize the rectangle.
// Set border color and width
rectSelectArea = new Rectangle
{
Stroke = Brushes.Blue,
StrokeThickness = 2,
Fill = Brushes.Transparent,
};
Canvas.SetLeft(rectSelectArea, startPoint.X);
Canvas.SetTop(rectSelectArea, startPoint.X);
canvas.Children.Add(rectSelectArea);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
throw ex;
}
}
但它抛出一个错误:
Cannot explicitly modify Children collection of Panel used as ItemsPanel for ItemsControl. ItemsControl generates child elements for Panel.
那么我该如何解决呢?
我试着用我的搜索同样的问题。并使用了对他们有用的解决方案。但错误仍然存在。有人能帮我吗。谢谢你。
最佳答案
Cannot explicitly modify Children collection of Panel used as ItemsPanel for ItemsControl. ItemsControl generates child elements for Panel.
这意味着您不能使用
Canvas.Children.Add
当您使用 Canvas
作为 ItemsPanel
对于 ItemsControl
.您应该在 ItemsControl.ItemsSource
的位置添加项目属性绑定(bind)到(在您的情况下为 ListRectangle
)。
关于c# - 使用 MVVM 将矩形添加到 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47644988/