首页 >后端开发 >C++ >如何使用MVVM在WPF画布上动态添加和定位矩形?

如何使用MVVM在WPF画布上动态添加和定位矩形?

Patricia Arquette
Patricia Arquette原创
2025-01-29 17:41:091063浏览

How to Dynamically Add and Position Rectangles on a WPF Canvas using MVVM?

使用 MVVM 在 WPF Canvas 上动态添加大小可变的矩形

本文的目标是在 MainWindow 的画布上渲染多个矩形,而无需在运行时知道它们的精确数量。这需要一种灵活的方法,利用 MVVM 原则。

ViewModel 中的抽象矩形表示

创建一个视图模型,定义矩形的抽象表示,包括其 x、y 坐标和尺寸的属性。

<code class="language-csharp">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>();

    // INotifyPropertyChanged implementation (required for data binding)
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}</code>

带有 ItemsControl 和 Canvas 的视图

在 MainWindow 中,创建一个 ItemsControl,其 ItemsPanel 为 Canvas。ItemsControl 将绑定到视图模型中的 RectItems 集合。

<code class="language-xml"><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></code>

通过这种设置,在画布上渲染的矩形数量将由视图模型中 RectItems 的数量决定。随着视图模型集合的变化,画布将自动更新以反映新的矩形。 请注意,为了使数据绑定正常工作,ViewModel需要实现INotifyPropertyChanged接口。 代码示例中已添加该接口的实现。

通过在 ViewModel 中向 RectItems 集合添加 RectItem 实例,可以在运行时动态添加矩形。

以上是如何使用MVVM在WPF画布上动态添加和定位矩形?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn