繁体   English   中英

执行ICommand时,属性设置为null

[英]Property is set to null when ICommand is executed

我有这个非常简单的代码,据我所知,我在整个程序中使用它。

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());
            }
        }
    }
}

我尝试将ComboBox的SelectedValue绑定到SelectedAthlete但是什么也没有发生,所以我决定尝试使用后面的代码。

如果我在设置时打印出SelectedAthlete的值,即在selectedAthlete = value行之后,那么我会得到一个正确的值,但是当ICommand踢入selectedAthlete的时间设置为null时。

我在用户控件后面的代码中设置SelectedAthlete的值,例如cbAthlete是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;
        }
    }
}

就像我之前说过的那样,我在程序的很多地方都这样做,并且效果很好,但是在这种情况下,我没有发现这是错误的。 任何帮助,不胜感激。 如果我在构造函数中设置selectedAthlete的值,则不会将其设置为null。 如果我在构造函数中对其进行初始化,即selectedAthlete = new Athlete(); 那是同一个故事。

任何和所有帮助,不胜感激。

如果您发布了XAML,这会有所帮助,但是我猜您忘了根据到目前为止发布的内容来设置DataContext。

当 itemSource 绑定到 Model (\

[英]How could one set the command property of a button in a View to an ICommand in the associated ViewModel when the itemSource is bound to a Model (\

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM