WPF多段线';将项添加到绑定的ObservableCollection时未调用s转换器
本文关键字:ObservableCollection 绑定 转换器 调用 添加 段线 WPF | 更新日期: 2023-09-27 18:00:33
我的应用程序有一条穿过一组点的线,每个点都有一个图标。Canvas元素中有以下XAML:
<!-- A route line -->
<Polyline Canvas.ZIndex="1" Stroke="Green" StrokeThickness="5" Points="{Binding SelectedRoute.Items, Converter={StaticResource routePointsConverter}}"></Polyline>
<!-- The icons on a route line -->
<ItemsControl Canvas.ZIndex="2" ItemsSource="{Binding SelectedRoute.Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding X, Converter={StaticResource canvasIconCenterConverter}}"/>
<Setter Property="Canvas.Top" Value="{Binding Y, Converter={StaticResource canvasIconCenterConverter}}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="Graphics'Icons'x.png" Width="20" Height="20"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
SelectedRoute.Items是一个ObservableCollection。问题是,将项添加到SelectedRoute.Items时,多段线不会更新。将项添加至Items时,会添加图标。如果我将SelectedRoute的绑定项更改为其他项,然后再更改,则该线也会正确绘制。这似乎是Polyline特有的问题。
当我调试时,我可以看到添加项目时没有调用多段线的转换器。为什么会发生这种情况?
注意,我已经找到了一个变通方法,但我想了解为什么它在所示的解决方案中不起作用。
WPF仅为ItemsControl.ItemsSource
属性注册INotifyCollectionChanged
更新。它实际上与Binding
扩展无关。您甚至可以直接将ItemsSource
属性分配(即不分配Binding
)给实现INotifyCollectionChanged
的集合,并且items控件将收到该集合更改的通知。
要更新Points
绑定,Items
属性必须激发PropertyChanged
事件。您可以在每次更改集合时"手动"启动它。