gpt4 book ai didi

WPF - 将鼠标悬停在一个元素上会显示另一个元素中的内容

转载 作者:行者123 更新时间:2023-12-04 19:25:28 25 4
gpt4 key购买 nike

我想实现一种效果,使我可以将鼠标悬停在 Button 上并让 TextBlock 更新其内容(通过绑定(bind))。使事情复杂化的是,按钮是 ItemsControl/DataTemplate 中定义的众多按钮之一。 TextBlock 在 ItemsControl 的范围之外。

问题的一些简化标记如下:

<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ItemsControl Grid.Row="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Title}"
Command="{Binding Command}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock x:Name="TitleTextBox" Grid.Row="1" />
</Grid>

在这个例子中,我可能想将数据项的“Title”属性绑定(bind)到 TextBlock 的“Text”属性。

我想我想点击按钮的 IsMouseOver,但我似乎无法正确连接它。

最佳答案

我认为如果没有一些代码,您将无法完成此任务...但是,您不需要使用代码隐藏。 “行为”对此很有效(旧学校 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”附加属性设置为悬停在其上的控件。编写行为应该足够简单,由您来完成。

编辑:要为项目设置事件处理程序,要做的第一件事简单明了:遍历 Items 属性中的项目并添加处理程序。

Mouse.AddMouseEnter(item, OnMouseEnter);

这适用于静态内容,但动态(在运行时添加和删除)内容将被遗漏。因此,接下来您必须跟踪对 Items 属性的更改。

((INotifyCollectionChanged)Items).CollectionChanged += OnItemsChanged;

在 CollectionChanged 处理程序中添加和删除项目时,根据需要添加或删除鼠标事件处理程序。

还有另一种解决方案。为此创建一个新的 HoverTrackingItemsControl,派生自 ItemsControl。在此控件中重写 GetContainerForItemOverride 方法以返回一个新的 HoverTrackingItem,它处理 MouseEnter/MouseLeave 以通知父 HoverTrackingItemsControl。此解决方案可能更易于实现,但它确实需要专门的控件,而行为解决方案更通用并且可以与任何 ItemsControl 类型(ItemsControl、ListBox、ComboBox 等)一起使用。

关于WPF - 将鼠标悬停在一个元素上会显示另一个元素中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/783965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com