在GDI +/WinForms中,我可以在Click()事件中使用图形对象:
AddPoint(p); //Add Point contains some code to make sure there is only 3 dots
foreach (Point p in PointList) {
DrawRectangle(p);
}
Invalidate();
Run Code Online (Sandbox Code Playgroud)
如果我在WPF中尝试类似的东西,它将不会清理我创建的点(我猜是因为WPF的工作原理).这意味着如果我检查确保一次只有三个点,并弹出最旧的点为新的点腾出空间,绘制的矩形仍然存在.
所以问题是,如何在WPF中创建允许我的东西
你正在以WinForms的方式做WPF.不要那样做.这就像在C++中编写VB代码一样.它只能以泪水结束.
要以WPF方式执行此操作,请使用数据绑定和视图模型类来执行"一次不超过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>
Run Code Online (Sandbox Code Playgroud)
然后我们只需要创建PointList.我们将使用普通的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);
}
}
Run Code Online (Sandbox Code Playgroud)
一块奶酪,是吗?所以最后一部分只是告诉XAML加载你的视图模型.在XAML的代码隐藏中,将DataContext设置为视图模型:
// Inside MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
// Add this line:
this.DataContext = new MainViewModel();
}
Run Code Online (Sandbox Code Playgroud)
既然已经实现了这一点,您可以通过调用viewModel.AddPoint或viewModel.PointList.Remove在代码中的任何位置添加/删除矩形,UI将自动更新以反映更改.
| 归档时间: |
|
| 查看次数: |
8312 次 |
| 最近记录: |