首页 > 解决方案 > WPF MVVM 如何从 ViewModel 中的视图访问矩形集合?

问题描述

我在 ViewModel 中有一个带有 RaisePropertyChanged 的​​按钮,它将形状中的矩形添加到界面和 ObservableCollection。

在视图中,我可以通过单击它们来移动或调整选定矩形的大小。它必须在 View 中,因为使用 Canvas,例如在 Window_Loaded 方法中。

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Rectangles = new List<Rectangle>();
            foreach (UIElement child in canvas1.Children)
            {
                if (child is Rectangle)
                    Rectangles.Add(child as Rectangle);
            }

            // Reverse the list so the Rectangles on top come first.
            Rectangles.Reverse();
        }

或 canvas1_MouseDown

        private void canvas1_MouseDown(object sender, MouseButtonEventArgs e)
        {

            FindHit(Mouse.GetPosition(canvas1));
            SetMouseCursor();
            if (MouseHitType == HitType.None) return;

            LastPoint = Mouse.GetPosition(canvas1);
            DragInProgress = true;
        }

不幸的是,List Rectangles 仅包含 UI 中的“静态”元素,而不是我通过单击按钮添加的元素。我要做的是用我在 ViewModel 中添加的矩形填充这个列表。任何建议都热烈欢迎。

我试图做的是计算添加的矩形并使用相同数量的新对象填充矩形,但看起来它应该在界面上具有对象的属性以允许交互。

标签: c#wpfmvvm

解决方案


这假设您在您的虚拟机中ObservableCollection调用Shapes了某种ShapeVM具有适当属性的对象(例如RectVM,具有宽度和高度等)

ItemsControl基础集合更改时,将自动将它们添加到视图中。

<ItemsControl ItemsSource="{Binding Shapes}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type vm:RectVM}">

            <Rectangle Canvas.Left="{Binding X}" 
                       Canvas.Top="{Binding Y}" 
                       Width="{Binding Width}"
                       Height="{Binding Height}" />

        </DataTemplate>
    </ItemsControl.Resources>

</ItemsControl>

请注意,如果您将拥有数千个形状,则这种绑定是不合适的,因为性能将是一个问题。


推荐阅读