![How to Dynamically Add and Position Rectangles on a WPF Canvas using MVVM?](https://img.php.cn/upload/article/000/000/000/173814367293612.jpg)
使用 MVVM 在 WPF Canvas 上动态添加大小可变的矩形
本文的目标是在 MainWindow 的画布上渲染多个矩形,而无需在运行时知道它们的精确数量。这需要一种灵活的方法,利用 MVVM 原则。
ViewModel 中的抽象矩形表示
创建一个视图模型,定义矩形的抽象表示,包括其 x、y 坐标和尺寸的属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class RectItem
{
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<RectItem> RectItems { get; set; } = new ObservableCollection<RectItem>();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
|
登录后复制
带有 ItemsControl 和 Canvas 的视图
在 MainWindow 中,创建一个 ItemsControl,其 ItemsPanel 为 Canvas。ItemsControl 将绑定到视图模型中的 RectItems 集合。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <ItemsControl ItemsSource= "{Binding RectItems}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Fill= "Black" Height= "{Binding Height}" Width= "{Binding Width}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType= "FrameworkElement" >
<Setter Property= "Canvas.Left" Value= "{Binding X}" />
<Setter Property= "Canvas.Top" Value= "{Binding Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
|
登录后复制
通过这种设置,在画布上渲染的矩形数量将由视图模型中 RectItems 的数量决定。随着视图模型集合的变化,画布将自动更新以反映新的矩形。 请注意,为了使数据绑定正常工作,ViewModel需要实现INotifyPropertyChanged
接口。 代码示例中已添加该接口的实现。
通过在 ViewModel
中向 RectItems
集合添加 RectItem
实例,可以在运行时动态添加矩形。
以上是如何使用MVVM在WPF画布上动态添加和定位矩形?的详细内容。更多信息请关注PHP中文网其他相关文章!