Question

I have this very simple code which, as far as I can see, I'm using all over my program where it works.

using CompetitionManager.DataAccess;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Windows;
using System.Windows.Input;

namespace CompetitionManager.ViewModel.CompetitionSetup
{
    public class AthleteListViewModel : ViewModelBase
    {
        private Athlete selectedAthlete;

        public ICommand AddAthleteCommand { get; private set; }

        public AthleteListViewModel()
        {
            AddAthleteCommand = new RelayCommand(() => ExecuteAddAthleteCommand());
        }

        public Athlete SelectedAthlete
        {
            get
            {
                return selectedAthlete;
            }
            set
            {
                if (selectedAthlete == value)
                    return;
                selectedAthlete = value;
                RaisePropertyChanged("SelectedAthlete");
            }
        }

        private void ExecuteAddAthleteCommand()
        {
            try
            {
                MessageBox.Show(SelectedAthlete.Id.ToString());
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
    }
}

I tried binding the SelectedValue of the ComboBox to SelectedAthlete but nothing happened so I decided to try using the code behind.

If I print out the value of SelectedAthlete as it is being set, i.e. after the selectedAthlete = value line then I get a correct value but when it's time for the ICommand to kick in selectedAthlete has been set to null.

I set the value of SelectedAthlete in the code behind of a user control like so where cbAthlete is a ComboBox.

using CompetitionManager.DataAccess;
using CompetitionManager.ViewModel;
using System.Windows.Controls;

namespace CompetitionManager.View.CompetitionSetup
{
    public partial class AthleteListView : UserControl
    {
        private ViewModelLocator locator = new ViewModelLocator();

        public AthleteListView()
        {
            InitializeComponent();
        }

        private void cbAthlete_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            locator.AthleteList.SelectedAthlete = (Athlete)cbAthlete.SelectedValue;
        }
    }
}

Like I said before, I do this in many places in my program and it works fine but in this case there is something I'm not seeing that's wrong. Any help greatly appreciated. If I set the value of selectedAthlete in the constructor then it's not set as null. If I initialize it in the constructor, i.e. selectedAthlete = new Athlete(); then it's the same story.

Any and all help greatly appreciated.

Était-ce utile?

La solution

It would help if you posted the XAML, but my guess is you forgot to set the DataContext based on what's posted so far.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top