C# WPF中ListBoxItem的MouseOver和IsSelected事件
我想让ListBoxItem触发两个事件,我可以从包含ListBox的外部usercontrol捕获它们。以下是我到目前为止得到的信息:C# WPF中ListBoxItem的MouseOver和IsSelected事件,c#,wpf,user-controls,listbox,listboxitems,C#,Wpf,User Controls,Listbox,Listboxitems,我想让ListBoxItem触发两个事件,我可以从包含ListBox的外部usercontrol捕获它们。以下是我到目前为止得到的信息: <ListBox Background="Black" Selected="listbox_selected" x:Name="listBox"> <ListBox.Resources> <Style
<ListBox
Background="Black"
Selected="listbox_selected"
x:Name="listBox">
<ListBox.Resources>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}"
Value="True">
<Setter Property="IsSelected" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Resources>
</ListBox>
现在,这将调用我的listbox\u Selected事件。我想要的是在结束时调用不同的事件或属性。为了清楚起见,我知道如何更改ListBoxItem本身的背景/前景或其他属性。但是我想改变祖父母的一些事情。你已经有了那个活动。。。如果我们不在子代树中的任何位置处理“Selected”(也有“UnSelected”)事件,则在任何祖先处处理来自
ListBoxItem
类的静态路由事件
<Window x:Class="...."
...
ListBoxItem.Selected="OnListBoxSelected">
<Grid>
<ListBox ItemsSource="{Binding Employees}"
DispalyMemberPath="Name"
selectedValuePath="ID" >
<ListBox.Resources>
<Style TargetType="ListBoxItem"
BasedOn="{StaticResource
{x:Type ListBoxItem}}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver,
RelativeSource={RelativeSource
Self}}"
Value="True">
<Setter Property="IsSelected"
Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Resources>
</ListBox>
</Grid>
</Window>
希望这有助于……为什么不从父级到子级绑定到IsSelected属性?反之亦然。这不起作用,因为这是我被卡住的地方。现在,给定上述解决方案,我如何处理实际的item selected事件?这样,我就劫持了OnListBoxSelected事件。我需要选择项目和项目悬停事件。我不懂“劫持”这个词?对我来说,这不是黑客或劫持。路由冒泡事件是WPF为您提供的解决方案,当您希望将某个事件从最深的子项(ListBoxItem)处理到最顶端的父项(ListBox)时。此外,您还没有解释为什么需要悬停事件。
private void OnListBoxSelected(object sender, RoutedEventArgs e)
{
var window = sender as Window;
var listBoxItem = e.OriginalSource as ListBoxItem;
var selectedItem = listBoxItem.DataContext;
}