开发者

Why am I needing to click twice on a WPF listbox item in order to fire a command?

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


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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜