我会推荐一种非常不同的方法,我相信它会达到你想要的结果,但会从你的视图模型中删除任何特定于控制的逻辑。
首先,我们需要一个表示画布上对象的逻辑视图模型。让我们假设它是国家,而画布是地图。也许虚拟机看起来像这样:
public class Country : PropertyChangedBase {
public string Name {get;set;}
public double X {get;set;}
public double Y {get;set;}
}
为简单起见,我省略了 INPC 位。接下来,我们的主视图模型(您问题中的 Presenter)可能如下所示:
public class Map : PropertyChangedBase {
public ObservableCollection<Country> Countries {get;set;}
}
我们将在每个国家/地区的画布上放置一个红点。如果是这样,那么您对应的 XAML 可能如下所示(省略根元素):
<ItemsControl ItemsSource="{Binding Countries}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Ellipse Fill="Red"
Width="16"
Height="16"
Canvas.Top="{Binding Y}"
Canvas.Left="{Binding X}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如果您需要处理事件,只需像往常一样将它们连接到 XAML 中。