0

我想让 ListBoxItem 触发两个事件,我可以从包含 ListBox 的外部用户控件中捕获它们。这是我到目前为止得到的:

<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_Selected 事件。我想要的是在 IsMouseOver 时调用不同的事件或属性。为了清楚起见,我知道如何更改 ListBoxItem 本身的背景/前景或其他属性。但我想改变祖父母的一些东西。

4

1 回答 1

1

您已经拥有该事件...ListBoxItem在任何祖先处处理名为“Selected”(并且还有“UnSelected”)的类的静态路由事件,前提是我们不在后代树中的任何地方处理“Selection”事件...

  <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>

在后面的代码中......

    private void OnListBoxSelected(object sender, RoutedEventArgs e)
    {
        var window = sender as Window;
        var listBoxItem = e.OriginalSource as ListBoxItem;
        var selectedItem = listBoxItem.DataContext;
    }

希望这可以帮助...

于 2011-10-20T05:31:48.903 回答