A bit of your code would have been helpful, but here's a dummy example of how to do select a ListBoxItem
using a click on a button, through the MVVM pattern.
public class MyViewModel : BaseViewModel // implements INotifyPropertyChanged
{
private ICommand _myCommand;
public ICommand MyCommand { get {return _myCommand;} private set { _myCommand = value; OnPropertyChanged(); }}
private ObservableCollection<int> _myObjects;
public ObservableCollection<int> MyObjects { get {return _myObjects;} private set {_myObjects = value; OnPropertyChanged();}}
private int _mySelectedObject;
public int MySelectedObject { get {return _mySelectedObject;} set {_mySelectedObject = value; OnPropertyChanged(); }}
public MyViewModel
{
MyCommand = new RelayCommand(SetSelectedObject); // the source code for RelayCommand may be found online.
}
private void SetSelectedObject(object obj)
{
int myInt = (int)obj;
MySelectedObject = myInt;
}
}
Some XAML parts have been erased in order to keep it simple. Do not simply copy/paste this snippet, adapt it to your code.
<UserControl x:Name="root" DataContext="{Binding MyViewModel, Source={StaticResource Locator.MyViewModel}}">
<ListBox ItemsSource="{Binding MyObjects}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding }"/>
<Button Command="{Binding MyCommand, ElementName=root}" CommandParameter="{Binding }"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</UserControl>
I have not tested this code. So there might be some mistakes. Don't hesitate to point these out, and I will update my code.
EDIT : Here is the source code for my RelayCommand implementation (modified from Telerik):
public class RelayCommand : ICommand
{
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private Action<object> _methodToExecute;
private Func<object, bool> _canExecuteEvaluator;
public RelayCommand(Action<object> methodToExecute, Func<object, bool> canExecuteEvaluator)
{
_methodToExecute = methodToExecute;
_canExecuteEvaluator = canExecuteEvaluator;
}
public RelayCommand(Action<object> methodToExecute)
: this(methodToExecute, null)
{
}
public bool CanExecute(object parameter)
{
if (_canExecuteEvaluator == null)
{
return true;
}
else
{
bool result = _canExecuteEvaluator.Invoke(parameter);
return result;
}
}
public void Execute(object parameter)
{
_umethodToExecute.Invoke(parameter);
}
}