簡體   English   中英

如何使用 MVVM 在雙擊列表框項上觸發命令?

[英]How to fire a command on double-click listbox item using MVVM?

當用戶雙擊列表框項時,我試圖啟動 ICommand。 另外,我正在嘗試使用 MVVM 模式來做到這一點。

在這個 XAML 中,按鍵“p”工作得很好。 當我雙擊列表框時,命令永遠不會啟動。 我已經設置了一個斷點來確認“PlayVideoCommand”不是通過雙擊調用的。 我是不是遺漏了什么,還是必須使用 Setter(我不熟悉)?

<ListBox Name="SmallVideoPreviews" Grid.Column="1" MaxHeight="965"
    ItemsSource="{Binding BrowseVideos}" 
    ItemTemplate="{StaticResource BrowseTemplate}">
    <ListBox.InputBindings>
        <KeyBinding Key="p" 
            Command="{Binding PlayVideoCommand}"
            CommandParameter="{Binding ElementName=SmallVideoPreviews, Path=SelectedItem}"/>
        <MouseBinding Gesture="LeftDoubleClick"
            Command="{Binding PlayVideoCommand}"
            CommandParameter="{Binding ElementName=SmallVideoPreviews, Path=SelectedItem}"/>
    </ListBox.InputBindings>
</ListBox>

雙擊和“p”都應該執行相同的命令。 使用鼠標時,我可以看到列表框項被選中。 我有一種預感,即 MouseBinding Command 屬性不是依賴屬性,但我不知道如何確認這一點。

您的示例中發生的事情是列表框本身對雙擊做出反應,但僅限於列表框項未涵蓋的部分區域。

您需要將事件處理程序綁定到listboxitem。

有一些方法可以執行此操作: 雙擊ListBox項以打開瀏覽器

關於為什么MVVM中的一點代碼隱藏不一定是一件可怕的事情的一些討論: 使用MVVM從WPF ListView項目中點擊雙擊事件

更多討論: http//social.msdn.microsoft.com/Forums/en-US/wpf/thread/9fb566a2-0bd6-48a7-8db3-312cd3e93340/

似乎ListBox不處理ListBoxItem上的雙擊。 這是一個很好的答案: 無法將Command綁定到ListBox

人們可能會爭辯說天氣與否代碼隱藏很糟糕,但它可以使用命令。 像這樣將 LeftDoubleClick 手勢添加到 ItemTemplate:

<UserControl.Resources>
    <DataTemplate x:Key="BrowseTemplate" >
        <StackPanel >
            <StackPanel.InputBindings>
                <MouseBinding Gesture="LeftDoubleClick"
                              Command="{Binding DataContext.PlayVideoCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Mode=OneWay}" 
                              CommandParameter="{Binding }" />
            </StackPanel.InputBindings>
            <TextBlock Text="{Binding }" Width="50" />
        </StackPanel>
    </DataTemplate>
</UserControl.Resources>

暫無
暫無

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

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