簡體   English   中英

使WPF ListBoxItems可選

[英]Making WPF ListBoxItems selectable

我有一個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>

@Natrium Nope,問題在這里有所不同,

  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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM