Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
WPF-将鼠标悬停在一个元素上会显示另一个元素中的内容_Wpf - Fatal编程技术网

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

WPF-将鼠标悬停在一个元素上会显示另一个元素中的内容,wpf,Wpf,我想实现一种效果,我可以将鼠标悬停在按钮上,让TextBlock更新其内容(通过绑定)。使事情复杂化的是,按钮是ItemsControl/DataTemplate中定义的许多按钮之一。TextBlock不在ItemsControl的范围内 问题的一些简化标记如下: <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDef

我想实现一种效果,我可以将鼠标悬停在按钮上,让TextBlock更新其内容(通过绑定)。使事情复杂化的是,按钮是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”属性绑定到TextBlock的“Text”属性

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

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

如果没有一些代码,我不相信您能够完成此任务。。。但是,您不需要使用codebehind。一种“行为”对这一点很管用(要么是老派的,要么是更现代的)。以下是使用附加行为修改后的标记的外观:

<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>
这适用于静态内容,但动态(在运行时添加和删除)内容将丢失。因此,接下来必须跟踪Items属性的更改

((INotifyCollectionChanged)Items).CollectionChanged += OnItemsChanged;
在CollectionChanged处理程序中添加和删除项时,根据需要添加或删除鼠标事件处理程序


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

如果我有误解,请纠正我,但听起来您似乎只想使用XAML来实现这一点?我敢肯定,单用XAML是做不到的。如果使用ListView而不是ItemsControl,则可以将TextBlock绑定到ListView的SelectedItem属性,但这仍然无法解决悬停问题。为此,您(我认为)需要使用代码隐藏。不过我不是WPF专家。谢谢你到目前为止的帮助。不过,我确实需要一些额外的帮助来处理所附的财产。在ItemsControl中的每个项目上连接MouseEnter/MouseExit的最佳方式是什么?我可以连接ItemsCommrol(而不是每个项目)的事件,但这仅在您将鼠标悬停在整个集合上一次时触发MouseEnter/Exit事件(除非我在按钮周围添加一些边距)。