Reputation: 10236
I am using MVVM prism and my code is as follows
<ListBox x:Name="myListBox" Grid.Row="0"
ItemsSource="{Binding Path=_mySOurce}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectionChanged="myListBox_SelectionChanged">
</ListBox>
<Button Grid.Row="1" x:Name="btnSelect"
Command="{Binding Path=SaveCommand}" Content="Select" Margin="396,0,10,0"></Button>
and in my code i have
public ICommand SaveCommand { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
this.SaveCommand = new DelegateCommand<object>(this.OnSaveClick, this.CanSaveExecute);
}
private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void OnSaveClick(object arg)
{
MessageBox.Show("Performed Click");
}
private bool CanSaveExecute(object arg)
{
if (myListBox.SelectedIndex > 0)
return true;
else return false;
}
I am not able to fire it at selection changed event.
What am I missing ?
Upvotes: 0
Views: 132
Reputation: 69959
If you're handling a UI event in your view model, then you're not using MVVM at all! Handling UI events in the view model completely breaks the separation of concerns that MVVM provides.
However, the short answer is this:
private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (SaveCommand.CanExecute(null)) SaveCommand.Execute(null);
}
A far better solution is to add another property to data bind to the ListBox.SelectedItem
property:
<ListBox x:Name="myListBox" Grid.Row="0" SelectedItem="{Binding CurrentItem}"
ItemsSource="{Binding Path=_mySOurce}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectionChanged="myListBox_SelectionChanged" />
Then the setter for that CurrentItem
property will be called whenever the SelectionChanged
event would be called:
public YourDataType CurrentItem
{
get { return currentItem; }
set
{
currentItem = value;
NotifyPropertyChanged("CurrentItem");
if (SaveCommand.CanExecute(null)) SaveCommand.Execute(null);
}
}
Upvotes: 1