【问题标题】:Why am I needing to click twice on a WPF listbox item in order to fire a command?为什么我需要在 WPF 列表框项上单击两次才能触发命令?
【发布时间】:2010-05-27 20:06:28
【问题描述】:

我正在尝试动态填充标准 WPF 列表框,并为列表框中的每个项目在单击时启动命令。 目前我有一个工作列表框,可以填充,每个项目都会触发正确的命令,但为了触发命令,我必须单击列表项两次。 即,单击一次以选择项目,然后单击实际文本以触发命令。

由于列表是动态创建的,我必须为列表项创建一个数据模板:

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

基本上,我如何消除点击两次的需要? 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. 或者,是否有更好的方法来动态填充列表框并将命令附加到每个列表项?

谢谢

【问题讨论】:

    标签: wpf listbox


    【解决方案1】:

    您确定是点击超链接文本本身吗?我运行你的代码没有任何困难,第一次点击链接对我有用。

    更新:如果您的命令需要知道点击了哪个列表项,您可以随时添加 CommandParameter:

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

    然后在您的执行方法中(因为您的 ListBox 绑定到字符串列表):

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

    更新 2:要自动选择项目,您可以将 ListBoxItem 作为您的 CommandParameter 传递:

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

    然后在你的命令中选择它:

    public void Execute(object parameter)
    {
        ListBoxItem itemClicked = (ListBoxItem)parameter;
        itemClicked.IsSelected = true;
        MessageBox.Show("You clicked on " + parameter.ToString());
    }
    

    【讨论】:

    • 是的,你是对的,当点击超链接文本时,该命令会触发,但看起来什么都不做。命令 Execute 方法需要选定的列表项才能执行操作,但是当仅单击超链接文本时,未选择列表项,因此无法执行操作。那么,改变列表项 IsSelected 属性的超链接上的数据触发器会起作用吗?超链接元素是列表项的子项是否存在问题?谢谢
    • @Donal,我已经用一个可能的解决方案更新了我的答案,虽然它没有选择项目
    • 太棒了!谢谢,您的代码有效。出于某种原因,我只是忽略了使用 CommandParameter。查找祖先绑定似乎也非常有用。
    猜你喜欢
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2017-09-23
    • 2018-02-01
    • 2014-08-08
    • 2019-05-30
    相关资源
    最近更新 更多