我有這個非常簡單的代碼,就我所見,我在我的程序中使用了所有的代碼。當ICommand被執行時,屬性被設置爲空
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是一個組合框。
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();
那麼它就是同一個故事。
任何和所有幫助非常感謝。
你說得對,我剛開始學習wpf,所以這些菜鳥的錯誤不時發生。 ;) –