代码之家  ›  专栏  ›  技术社区  ›  Dominic K

在WPF中绘制和删除形状

  •  2
  • Dominic K  · 技术社区  · 16 年前

    AddPoint(p); //Add Point contains some code to make sure there is only 3 dots
    foreach (Point p in PointList) {
        DrawRectangle(p);
    }
    Invalidate();
    

    如果我在WPF中尝试类似的东西,它将不会清除我创建的点(我猜是因为WPF是如何工作的)。这意味着,如果我检查确保一次只有三个点,然后弹出最老的点为新的点腾出空间,绘制的矩形仍然存在。

    所以问题是,如何在WPF中创建允许我

    • 在一点上画一个矩形
    • 在WPF画布中删除超过3个矩形/点
    2 回复  |  直到 16 年前
        1
  •  9
  •   Judah Gabriel Himango    16 年前

    你在用WinForms的方式做WPF。别那么做。就像在C++中编写VB代码一样。它只能以眼泪结束。

    为了用WPF的方式实现这一点,使用databinding和视图模型类来实现“一次不超过3个”的逻辑,然后,对于UI,只需绑定到视图模型中的PointList。

    我的XAML应该是这样的。注意,我只是使用ItemsControl和Canvas,然后将ItemsSource绑定到PointList:

    <Window x:Class="WpfTester.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
    
        <ItemsControl ItemsSource="{Binding Path=PointList}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Rectangle Fill="Red" Width="25" Height="25" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemContainerStyle>
                <Style>
                    <Setter Property="Canvas.Left" Value="{Binding Path=X}" />
                    <Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Window>
    

    然后我们只需要创建点列表。我们将使用普通的WPF方法:视图模型类来保存点列表:

    class MainViewModel
    {
        public MainViewModel()
        {
            PointList = new ObservableCollection<Point>();
    
            // Some example data:
            AddPoint(new Point(10, 10));
            AddPoint(new Point(200, 200));
            AddPoint(new Point(500, 500));
        }
    
        public ObservableCollection<Point> PointList { get; private set; }
    
        public void AddPoint(Point p)
        {
            // 3 at most, please!
            if (PointList.Count == 3)
            {
                PointList.RemoveAt(0);
            }
            PointList.Add(p);
        }
    }
    

    一块奶酪,是吗?最后一部分只是告诉XAML加载视图模型。在XAML的代码背后,将DataContext设置为视图模型:

    // Inside MainWindow.xaml.cs
    public MainWindow()
    {
        InitializeComponent();
    
        // Add this line:
        this.DataContext = new MainViewModel();
    }
    

    现在已经准备好了,只需调用viewModel.AddPoint 或者viewModel.PointList.Remove,UI将自动更新以反映更改。

        2
  •  1
  •   user180326 user180326    16 年前

    我将使用wpf数据绑定将画布的内容绑定到存储在elsewere中的矩形集合。如果您想进行严肃的WPF开发,那么您无论如何都需要学习数据绑定。

    编辑:当然只存储矩形,数据绑定应该为每个矩形创建一个形状。