【问题标题】:Set Interaction.Triggers to ListBoxItem将 Interaction.Triggers 设置为 ListBoxItem
【发布时间】:2013-10-21 07:07:15
【问题描述】:

我已将 Interaction.Triggers 设置为 ListBox 并在 'SelectionChanged' 事件发生时执行相应的 TargetedTriggerAction,如下所示。

<ListBox x:Name="WorksheetListBox" ItemsSource="{Binding WorkSheetCollection}"
                             ItemTemplate="{StaticResource workSheetTemplate}">                              
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
        <action:WorksheetListBoxAction />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</ListBox>

但我的要求是我需要将 Interaction.Triggers 设置为 ListBoxItem 的“PreviewMouseDown”事件(注意:通过 ItemsSource 填充的 ListBox)

【问题讨论】:

  • &lt;i:EventTrigger EventName="PreviewMouseDown"&gt; ....
  • 嗨 Omribitan,如果我将“SelectionChanged”替换为“PreviewMouseDown”,它只会触发 ListBox,而不是 ListBoxItem。我需要为 ListBoxItem 设置它。所以请建议我必须在哪里为 ListBoxItem 设置这个“事件触发器”

标签: c# wpf xaml listbox listboxitem


【解决方案1】:

你可以通过 ListBoxItem 上的 PreviewMouseDown 事件来实现

<ListBox ItemsSource="{StaticResource Data}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button Name="TaskButton" Content="{Binding}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <EventSetter Event="PreviewMouseDown"
                                 Handler="ItemOnPreviewMouseDown" />
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>

        private void ItemOnPreviewMouseDown(
            object sender, MouseButtonEventArgs e)
        {

            ((ListBoxItem) sender).IsSelected = true;

        }

【讨论】:

    【解决方案2】:

    你可以试试这样的:

        <Style TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <EventTrigger RoutedEvent="PreviewMouseDown">
                    <EventTrigger.Actions>
                        <action:WorksheetListBoxAction />
                    </EventTrigger.Actions>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    

    【讨论】:

    • 这怎么可能工作,甚至被标记为接受的答案?对于初学者,action:WorksheetListBoxAction 是一个System.Windows.Interactivity.TriggerAction,它不能用作EventTriggerStyle.Triggers 中的操作。也无法重写动作类以从System.Windows.TriggerAction 派生,这在这种情况下可以工作,但不幸的是没有公共构造函数可以派生。
    【解决方案3】:
      <ListBox.Triggers>
                        <EventTrigger RoutedEvent="PreviewMouseDown">
                            <action:WorksheetListBoxAction />
                        </EventTrigger>
                    </ListBox.Triggers>
    

    您也可以在不使用 Interactivity.dll 的情况下进行事件处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      相关资源
      最近更新 更多