我的wpf窗口中有一个 ListBox ,它绑定到 ObervableCollection 。如果有人点击 ListBox 的元素(就像链接一样),我想打开浏览器。谁能告诉我怎么做?我发现了listboxviews的一些东西,它只是以这种方式工作还是只使用 ListBox

你的

塞巴斯蒂安

有帮助吗?

解决方案

您可以为 ListBox添加样式。 ItemContainerStyle ,并在那里添加 EventSetter

<ListBox>
    ....
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
            <EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

ListBoxItem_MouseDoubleClick是您的代码中的一个方法,其中包含 MouseDoubleClick

其他提示

我想解决这个问题而不需要在代码隐藏中处理listBoxItem双击事件,我不想重写listBoxItem样式(或者首先定义要覆盖的样式)。我想在listBox被双击时发出命令。

我创建了一个附属属性(代码非常具体,但您可以根据需要进行概括):

public class ControlItemDoubleClick : DependencyObject {
public ControlItemDoubleClick()
{

}

public static readonly DependencyProperty ItemsDoubleClickProperty =
    DependencyProperty.RegisterAttached("ItemsDoubleClick",
    typeof(bool), typeof(Binding));

public static void SetItemsDoubleClick(ItemsControl element, bool value)
{
    element.SetValue(ItemsDoubleClickProperty, value);

    if (value)
    {
        element.PreviewMouseDoubleClick += new MouseButtonEventHandler(element_PreviewMouseDoubleClick);
    }
}

static void element_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ItemsControl control = sender as ItemsControl;

    foreach (InputBinding b in control.InputBindings)
    {
        if (!(b is MouseBinding))
        {
            continue;
        }

        if (b.Gesture != null
            && b.Gesture is MouseGesture
            && ((MouseGesture)b.Gesture).MouseAction == MouseAction.LeftDoubleClick
            && b.Command.CanExecute(null))
        {
            b.Command.Execute(null);
            e.Handled = true;
        }
    }
}

public static bool GetItemsDoubleClick(ItemsControl element)
{
    return (bool)element.GetValue(ItemsDoubleClickProperty);
}

}

然后我使用附加属性和目标命令声明我的ListBox:

<ListBox ItemsSource="{Binding SomeItems}"
     myStuff:ControlItemDoubleClick.ItemsDoubleClick="true">
<ListBox.InputBindings>
    <MouseBinding MouseAction="LeftDoubleClick" Command="MyCommand"/>
</ListBox.InputBindings>
</ListBox>

希望这有帮助。

我已经更新了AndrewS解决方案,以解决在双击列表框中的任何位置时触发执行命令的问题:

public class ControlDoubleClick : DependencyObject
{
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ControlDoubleClick), new PropertyMetadata(OnChangedCommand));

    public static ICommand GetCommand(Control target)
    {
        return (ICommand)target.GetValue(CommandProperty);
    }

    public static void SetCommand(Control target, ICommand value)
    {
        target.SetValue(CommandProperty, value);
    }

    private static void OnChangedCommand(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Control control = d as Control;
        control.PreviewMouseDoubleClick += new MouseButtonEventHandler(Element_PreviewMouseDoubleClick);
    }

    private static void Element_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        Control control = sender as Control;
        ICommand command = GetCommand(control);

        if (command.CanExecute(null))
        {
            command.Execute(null);
            e.Handled = true;
        }
    }
}

在XAML中,ListBox的声明是:

<ListBox ItemsSource="{Binding MyItemsSource, Mode=OneWay}">                    
      <ListBox.ItemContainerStyle>
                    <Style>                            
                        <Setter Property="behaviours:ControlDoubleClick.Command" Value="{Binding DataContext.MyCommand,
                                    RelativeSource={RelativeSource FindAncestor, 
                                    AncestorType={x:Type UserControl}}}"/>
                     </Style>  
     </ListBox.ItemContainerStyle>
</ListBox>

我使用Expression SDK 4.0

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<i:Interaction.Triggers>
  <i:EventTrigger EventName="MouseDoubleClick" SourceName="CaravanasListBox">
     <i:InvokeCommandAction Command="{Binding AccionesToolbarCommand}" CommandParameter="{x:Static local:OpcionesBarra.MostrarDetalle}" />
   </i:EventTrigger>
</i:Interaction.Triggers>

Jaimir G。

这是一种在 ListBox ListView 上完成的行为。这是基于Andrew S.和Vadim Tofan的答案,伟大的工作人员!

public class ItemDoubleClickBehavior : Behavior<ListBox>
{
    #region Properties
    MouseButtonEventHandler Handler;
    #endregion

    #region Methods

    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.PreviewMouseDoubleClick += Handler = (s, e) =>
        {
            e.Handled = true;
            if (!(e.OriginalSource is DependencyObject source)) return;

            ListBoxItem sourceItem = source is ListBoxItem ? (ListBoxItem)source : 
                source.FindParent<ListBoxItem>();

            if (sourceItem == null) return;

            foreach (var binding in AssociatedObject.InputBindings.OfType<MouseBinding>())
            {
                if (binding.MouseAction != MouseAction.LeftDoubleClick) continue;

                ICommand command = binding.Command;
                object parameter = binding.CommandParameter;

                if (command.CanExecute(parameter))
                    command.Execute(parameter);
            }
        };
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.PreviewMouseDoubleClick -= Handler;
    }

    #endregion
}

这是用于查找父级的扩展类。

public static class UIHelper
{
    public static T FindParent<T>(this DependencyObject child, bool debug = false) where T : DependencyObject
    {
        DependencyObject parentObject = VisualTreeHelper.GetParent(child);

        //we've reached the end of the tree
        if (parentObject == null) return null;

        //check if the parent matches the type we're looking for
        if (parentObject is T parent)
            return parent;
        else
            return FindParent<T>(parentObject);
    }
}

用法:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:coreBehaviors="{{Your Behavior Namespace}}"


<ListView AllowDrop="True" ItemsSource="{Binding Data}">
    <i:Interaction.Behaviors>
       <coreBehaviors:ItemDoubleClickBehavior/>
    </i:Interaction.Behaviors>

    <ListBox.InputBindings>
       <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding YourCommand}"/>
    </ListBox.InputBindings>
</ListView>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top