如何访问Mainpage.xaml.cs中ItemViewModel类中定义的属性

时间:2014-06-06 10:19:34

标签: c# wpf xaml windows-phone-8

我有MedicicineModel(MainViewModel类)和MedicineData(ItemViewModel类)。我在MedicineData类中定义了三个属性,如下所示:

namespace MedicinePlus.ViewModels
{
    public class MedicineData
    {
        public string ProblemName { get; set; }
        public string ProblemDesc { get; set; }
        public string ProblemImageFilePath { get; set; }
    }
}

MedicineModel类如下:

namespace MedicinePlus.ViewModels
{
public class MedicineModel
{
    public List<MedicineData> Problems { get; set; }
    public MedicineModel()
    {
        this.Problems = new List<MedicineData>();
    }

    public bool IsDataLoaded { get; set; }

    public void LoadData()
    {
    //place design time datat here
        IsDataLoaded = true;
        this.Problems.Add(new MedicineData() { ID = 0, ProblemName = "Fever",  ProblemDesc = "rise in body temperature", ProblemImageFilePath = "/Assets/Images/fever.png" });
        this.Problems.Add(new MedicineData() { ID = 2, ProblemName = "sprain", ProblemDesc = "Caused due to muscle pull", ProblemImageFilePath = "/Assets/Images/sprain1.png" });
        this.Problems.Add(new MedicineData() { ID = 3, ProblemName = "bruise", ProblemDesc = "irritation in the concerned area", ProblemImageFilePath = "/Assets/Images/headache.png" });

    }

}
}

MainPage.xaml.cs如下:

namespace MedicinePlus
{
public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Set the data context of the listbox control to the sample data
        DataContext = App.ViewModel;

        // Sample code to localize the ApplicationBar
        BuildLocalizedApplicationBar();
    }

    // Load data for the ViewModel Items
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (!App.ViewModel.IsDataLoaded)
        {
            App.ViewModel.LoadData();
        }
    }
private void submitMenu_Click(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}

QUERY:现在我想在submit_Click事件处理程序的代码块中访问ProblemName,ProblemDesc和ProblemImgPath。我该怎么做

2 个答案:

答案 0 :(得分:0)

您必须创建MedicineData

的实例
MedicineData medicineData = new medicineData();

然后您可以像以下一样访问它们:

medicineData.ProblemName
medicineData.ProblemDesc 

medicineData.ProblemImageFilePath 

答案 1 :(得分:0)

您还没有真正提供足够的信息让我们明确回答,所以我们所能做的就是猜测。例如,App.ViewModel属性中的对象是什么?它是MedicineModel实例吗?如果是,那么你似乎忽视了这个属性。您当然可以使用它访问您的视图模型及其数据吗?:

private void submitMenu_Click(object sender, EventArgs e)
{
    MedicineModel viewModel = App.ViewModel;
    List<MedicineData> problems = viewModel.Problems;
    string problemName = problems[0].ProblemName;
}

如果这不是你所追求的,那么也许你已经足够好,可以更准确地告诉我们你的需求和你遇到的问题。