tags:

views:

193

answers:

1

Hi, I'm trying to make a standard WPF listbox be dynamically filled, and for each item in the list box to launch a command when clicked. Currently I have a working listbox, which can be filled and each item will fire the correct command, but in order to fire the command I have to click the list item twice. i.e, Click once to select the item, then click on the actual text to fire the command.

As the list is dynamically created, I had to create a data template for the list items:

<ListBox.ItemTemplate>
      <DataTemplate>
        <TextBlock Margin="4,2,4,2">
          <Hyperlink TextDecorations="None" Command="MyCommands:CommandsRegistry.OpenPanel">
            <TextBlock Text="{Binding}" Margin="4,2,4,2"/>
          </Hyperlink>
        </TextBlock>
      </DataTemplate>
 </ListBox.ItemTemplate>

Basically, how do I remove the need to click twice? I have tried to use event triggers to fire the click event on the hyperlink element when the list box item is selected, but I can't get it to work. Or, is there a better approach to dynamically fill a listbox and attach commands to each list item?

Thanks

A: 

Are you definitely clicking on the hyperlink text itself? I had no difficulty running your code and the first click on the link worked for me.

Update: if your command needs to know which list item was clicked, you could always add a CommandParameter:

<Hyperlink TextDecorations="None" Command="my:CommandsRegistry.OpenPanel" CommandParameter="{Binding}">

then in your execute method (since your ListBox is bound to a list of strings):

public void Execute(object parameter)
{
    MessageBox.Show("You clicked on " + parameter.ToString());
}

Update 2: To auto select items, you could pass the ListBoxItem as your CommandParameter:

<Hyperlink TextDecorations="None" Command="my:CommandsRegistry.OpenPanel" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}">

and then select it in your command:

public void Execute(object parameter)
{
    ListBoxItem itemClicked = (ListBoxItem)parameter;
    itemClicked.IsSelected = true;
    MessageBox.Show("You clicked on " + parameter.ToString());
}
Mark Heath
Yes, you're right, the command does fire when just clicking on the hyperlink text, but gives the appearance of doing nothing. The command Execute method needs the selected list item in order to perform an action, but when clicking on just the hyperlink text the list item is not selected and so can't perform the action. So, would a data trigger on the hyperlink which changes the list item IsSelected property work? is it a problem that the hyperlink element is a child of the list item?Thanks
Donal
@Donal, I've updated my answer with a possible solution for you, although it doesn't select the item
Mark Heath
Great! Thanks, your code worked. For some reason I just neglected using CommandParameter. The find ancestor binding seems really useful too.
Donal