【问题标题】:MouseOver and IsSelected events for ListBoxItem in WPFWPF 中 ListBoxItem 的 MouseOver 和 IsSelected 事件
【发布时间】:2011-10-19 18:32:20
【问题描述】:

我想让 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 本身的背景/前景或其他属性。但我想改变祖父母的一些东西。

【问题讨论】:

  • 为什么不绑定到 IsSelected 属性从父到子?反之亦然。

标签: c# wpf user-controls listbox listboxitems


【解决方案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;
    }

希望这会有所帮助...

【讨论】:

  • 这不起作用,因为这是我卡住的地方。现在,给出上述解决方案,我该如何处理真正的项目选择事件?有了这个,我劫持了 OnListBoxSelected 事件。我需要项目选择和项目悬停事件。
  • 我听不懂hijacking这个词?对我来说,这不是黑客攻击或劫持。当您希望从最深的子级 (ListBoxItem) 到最顶层的父级 (ListBox) 处理某些事件时,路由冒泡事件是 WPF 为您提供的解决方案。而且你还没有解释为什么你也需要悬停事件。
猜你喜欢
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多