How can I implement SelectionChanged in MVVM ListBox Silverlight

The ListBox control does not implement the Command property. I need to attach some functions to the SelectionChanged event. Does anyone know how I can do this? Please help me

+5
source share
5 answers

I prefer to use binding to SelectedItemand implement any functionality in setting 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.
        }
    }
}
+18
source

, MVVM , , Command Property Button, , , "" XMAL

<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>

dll Syatem.Windows.Interactivity   xaml,

 xmlns:Local="clr-namespace:System.Windows.Interactivityassembly=System.Windows.Interactivity"

ViewModel Con

 public ViewModel123()
    {
         MyCommand = new RelayCommand<string>(TestMethod);

    }

TestMethod,

 private void TestMethod(string parameter)
    {
        MessageBox.Show(parameter);
    }

, .

+15

:

  • SelectedItem ListBox (.. ) , Cameron MacFarland.
  • , , , Pedro Lamas.
  • , - , ListBox. SelectionChanged ( , ).
+2

RelayCommand. MVVM Light Toolkit RelayCommand CommandManager . , .

, , , , . SelectedValue ListBox .

0

All Articles