Clique duas vezes em um item da ListBox para abrir um navegador
-
03-07-2019 - |
Pergunta
eu tenho um ListBox
na minha janela WPF que se liga a um ObervableCollection
. Eu quero abrir o navegador se alguém clicar em um elemento do ListBox
(Assim como um link). Alguém pode me dizer como fazer isso? Encontrei algo com o ListBoxViews, ele só funciona dessa maneira ou existe uma maneira apenas usando o ListBox
?
Seu
Sebastian
Solução
Você pode adicionar um estilo a Listbox.itemContainersTyle, e adicione um Eventsetter lá:
<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 é um método em seu código por trás da assinatura correta para Mousedoubleleclick.
Outras dicas
Eu queria resolver isso sem precisar lidar com o evento ListBoxItem Double Click no código-behind, e não queria substituir o estilo ListBoxItem (ou definir o estilo a ser substituído em primeiro lugar). Eu queria apenas demitir um comando quando a caixa de listagem era dobrada.
Eu criei uma propriedade anexada como assim (o código é muito específico, mas você pode generalizá -lo conforme necessário):
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);
}
}
Declaro então minha caixa de listagem com a propriedade anexada e meu comando de destino:
<ListBox ItemsSource="{Binding SomeItems}"
myStuff:ControlItemDoubleClick.ItemsDoubleClick="true">
<ListBox.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="MyCommand"/>
</ListBox.InputBindings>
</ListBox>
Espero que isto ajude.
Atualizei a solução Andrews para resolver o problema com a execução do comando se clicar duas vezes em qualquer lugar na caixa de listagem:
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;
}
}
}
E no xaml, a declaração para a caixa de listagem é:
<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>
Eu usei expressão 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.
Aqui está um comportamento que faz isso em ambos ListBox
e ListView
. Isso é baseado em respostas de Andrew S. e Vadim Tofan, ótimos empregos caras!
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
}
Aqui está a classe de extensão usada para encontrar o pai.
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);
}
}
Uso:
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>