Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I realize SelectionChanged in MVVM ListBox Silverlight

The ListBox control does not implement a Command property. I have to attach some functionality to the SelectionChanged event. Somebody knows how can I do it? Please help me

like image 838
Thomas Wingfield Avatar asked Jan 01 '12 11:01

Thomas Wingfield


2 Answers

I prefer using a binding to the SelectedItem and implementing any functionality in the setting of the binding property.

<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />

...

public class ViewModel
{
    public IEnumerable<Item> Items { get; set; } 

    private Item selectedItem;
    public Item SelectedItem
    {
        get { return selectedItem; }
        set
        {
            if (selectedItem == value)
                return;
            selectedItem = value;
            // Do logic on selection change.
        }
    }
}
like image 81
Cameron MacFarland Avatar answered Oct 09 '22 00:10

Cameron MacFarland


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);
    }

i hope this may help u.

like image 41
Dhaval Patel Avatar answered Oct 09 '22 01:10

Dhaval Patel