Code snippet: WPF UWP ListView SelectionChanged Event Handling in ViewModel

Solution from Dhaval Patel in Sliverlight application works perfectly on my WPF application. I prefer his idea because it is more clear and cleaner than other solutions that  I have came with. The event handling approach explained as -"This is the way where You can Reach the Selection changed events in Your MVVM Application First Of all i tell you that Command Property only work in Button now we have to Explicitly binding that property in our Selection Changed event like List box or combo box in Your XMAL file"
<ListBox Name="MyListBox" ItemsSource="{Binding ListItems}" Height="150" Width="150" Margin="281,32,-31,118">

        <Local:Interaction.Triggers>
            <Local:EventTrigger EventName="SelectionChanged">
                <Local:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}"/>
            </Local:EventTrigger>
        </Local:Interaction.Triggers>
    </ListBox>
for this you have to add dll Syatem.Windows.Interactivity now u have to add references in your xaml file namespace like
 xmlns:Local="clr-namespace:System.Windows.Interactivityassembly=System.Windows.Interactivity"

in your ViewModel Class you have to define your Command in Con structure
 public ViewModel123()
    {
         MyCommand = new RelayCommand<string>(TestMethod);

    }
now create the TestMethod method which can handle the selection changed event
 private void TestMethod(string parameter)
    {
        MessageBox.Show(parameter);
    }

In UWP:

Import 
 xmlns:interactivity="using:Microsoft.Xaml.Interactivity"  
 xmlns:core="using:Microsoft.Xaml.Interactions.Core"  
   

And following snippet should works -
       <interactivity:Interaction.Behaviors>  
         <core:EventTriggerBehavior EventName="SelectionChanged">  
           <core:InvokeCommandAction Command="{Binding Path=MyCommand}" CommandParameter="{Binding ElementName=SketchPaletteListView, Path=SelectedItem}"/>  
         </core:EventTriggerBehavior>  
       </interactivity:Interaction.Behaviors>  

Comments

Popular posts from this blog

[Code Snippet] Assert Exception in private methods using PrivateObject

Update WPF Interaction Triggers in from .Net Framework 4.8 to .Net 5

[Code snippet] How to set value of private variable in Unit Test Using Reflection ?