Home > database >  WPF - binding event to the ViewModel
WPF - binding event to the ViewModel

Time:08-17

I have a stack panel for which I need a mouse event to be handled in the ViewModel but the binding doesn't work - the command isn't found although the other elements are also binded to the ViewModel and they work. Here is the xaml:

<Window.DataContext>
        <vm:Ticker/>
</Window.DataContext>


 <ListView Grid.Row="3"
     ItemsSource ="{Binding TickersCollectionView}">
   <ListView.ItemTemplate>
     <DataTemplate>
        <StackPanel Orientation="Horizontal" 
                    Name="STPListView">

                  <i:Interaction.Triggers>
                     <i:EventTrigger EventName="MouseLeftButtonDown">
                       <i:InvokeCommandAction
                          Command="{Binding MouseLeftButtonDownCommand}"
                          CommandParameter="{Binding ElementName=STPListView}"/>
                     </i:EventTrigger>
                  </i:Interaction.Triggers>
          <TextBlock 
              Width="130" 
              Text="{Binding Market}"
              Foreground="WhiteSmoke"/>
         <TextBlock 
              Width="110" 
              Text="{Binding Price}"
              Foreground="{Binding LastPrice, Converter={StaticResource BoolToForeground}}"/>
      </StackPanel>
    </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

The command is a property of the ViewModel. How can I bind it?

CodePudding user response:

If the MouseLeftButtonDownCommand property is defined in the same view model as the TickersCollectionView property, you should bind to it using a RelativeSource:

Command="{Binding DataContext.MouseLeftButtonDownCommand,
    RelativeSource={RelativeSource AncestorType=ListView}}"
  • Related