【问题标题】:Making WPF ListBoxItems selectable使 WPF ListBoxItems 可选择
【发布时间】:2009-10-07 06:57:22
【问题描述】:

我有一个ListBox,定义了一个相当简单的ItemTemplate - 包含一个TextBlock 和一个Button。这显示如预期,但有一个问题。当我单击ListBoxItem 的内容(即文本或按钮)时,不会在ListBox 中选择该行。如果我单击它的行的空白部分。当我单击该行的任意位置时,我希望选择ListBoxItem。实现这一目标需要什么?

<ListBox ItemsSource="{Binding SomeElements}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem Selected="ListBoxItem_Selected">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Title}"></TextBlock>
                    <Button>Click</Button>
                </StackPanel>                                                
            </ListBoxItem>                                            
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

【问题讨论】:

标签: .net wpf listbox selecteditem listboxitem


【解决方案1】:

@Natrium 不,这里的问题不同,

  1. 您需要删除 DataTemplate 中的 ListBoxItem。 DataTemplate 不能有项 ListBoxItem,它将无法正常工作。无论您在 DataTemplate 中定义什么,都会在运行时自动放入 ListBoxItem 中,因此在您的情况下,这就是它被创建的内容。
ListBoxItem
    DataTemplate
        ListBoxItem
            StackPanel...
  1. 如果你想跟踪选择事件,那么你应该只捕捉 ListBox.SelectionChange 事件,你不需要跟踪 ListBoxItem_Selected。

把你的代码改成这个。

<ListBox ItemsSource="{Binding SomeElements}">
    <ListBox.ItemTemplate>
        <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Title}"></TextBlock>
                    <Button>Click</Button>
                </StackPanel>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

【讨论】:

  • 完美..!感谢您澄清这一点:-)
猜你喜欢
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
相关资源
最近更新 更多