문제

나는있다 ListBox 내 WPF 창에서 ObervableCollection. 누군가가 요소를 클릭하면 브라우저를 열고 싶습니다. ListBox (링크처럼). 누군가가 이것을하는 방법을 말해 줄 수 있습니까? ListBoxViews로 무언가를 찾았는데, 이런 식으로 만 작동합니까, 아니면 ListBox?

당신 것

세바스찬

도움이 되었습니까?

해결책

스타일을 추가 할 수 있습니다 ListBox.ItemContainerstyle, 그리고 추가하십시오 이벤트 세터 거기:

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

다른 팁

Code-Behind에서 ListBoxItem Double Click 이벤트를 처리 할 필요없이 이것을 해결하고 싶었고 ListBoxItem 스타일을 무시할 필요가 없었습니다 (또는 처음에는 스타일을 정의 할 필요가 없습니다). Listbox가 이중으로 표시되었을 때 명령을 발사하고 싶었습니다.

SO와 같은 첨부 된 속성을 만들었습니다 (코드는 매우 구체적이지만 필요에 따라 일반화 할 수 있습니다).

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>

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