我不相信没有代码你就能完成这项工作。..但是,您不需要在后面使用代码。一种“行为”对此很有效(要么是老派
attached behavior
,或更现代的
Blend Behavior
).以下是使用附加行为修改后的标记的样子:
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ItemsControl x:Name="Buttons" Grid.Row="0" ext:Hover.TrackChildItems="true">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Title}"
Command="{Binding Command}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock x:Name="TitleTextBox"
Grid.Row="1"
Text="{Binding ElementName=Buttons, Path=ext:Hover.Item.Content}" />
</Grid>
这里,附加的行为“Hover.TrackChildItems”用于监视相应的鼠标事件,并将只读的“Hover.Item”附加属性设置为悬停在其上的控件。写行为应该足够简单,留给你。
Mouse.AddMouseEnter(item, OnMouseEnter);
这对于静态内容很好,但动态(在运行时添加和删除)内容将被忽略。因此,接下来您必须跟踪Items属性的更改。
((INotifyCollectionChanged)Items).CollectionChanged += OnItemsChanged;
在CollectionChanged处理程序中添加和删除项目时,根据需要添加或删除鼠标事件处理程序。
还有另一种解决方案。为此创建一个新的HoverTrackingItems控件,该控件派生自Items控件。在此控件中,重写GetContainerForItemOverride方法以返回一个新的HoverTrackingItem,该方法处理MouseEnter/MouseLeave以通知父级HoverTracking_Items控件。此解决方案可能更容易实现,尽管它确实需要专门的控件,而行为解决方案更通用,可以与任何Items control类型(Items control、列表框、组合框等)一起使用。