Reputation: 95
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
Upvotes: 5
Views: 14321
Reputation: 7601
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.
Upvotes: 16
Reputation: 1564
Basically you have a few options:
SelectionChanged
event and execute a command (the command could be a dependency property exposed by the behavior).Upvotes: 2
Reputation: 71856
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.
}
}
}
Upvotes: 19
Reputation: 1425
I would suggest using RelayCommand
. Either use the MVVM Light Toolkit or just use the RelayCommand
and CommandManager
classes from Josh Smith's implementations. I personally use just the two classes, so I don't need the entire toolkit.
While this will definitely work, there might be an easier way depending on what you are doing. It might just be easier to bind an object to the SelectedValue
of the ListBox
and listen for that value to change.
Upvotes: 0
Reputation: 7233
Think this post from Laurent Bugnion will help you solve the problem:
The post above mentions the DataGrid but I do think it will work with the ListBox too!
Best regards and Happy New Year!! :)
Upvotes: 1