使WPF ListBoxItems可选

时间:2009-10-07 06:57:22

标签: .net wpf listbox selecteditem listboxitem

我的ListBox定义了一个相当简单的ItemTemplate - 包含TextBlockButton。这显示出预期,但有一个问题。当我点击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>

1 个答案:

答案 0 :(得分:4)

<@> @Natrium Nope,问题在这里有所不同,

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

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