Friday, August 19, 2016

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>  

.NET , C# , WPF

0 comments :

Post a Comment

 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me